Skip to content

feature: support global type-based rules #1161

@carlosV2

Description

@carlosV2

Description

I'm working with MikroORM and, for whatever reason, class-transformer is unable to transform ArrayCollection. When attempted, it throws Class constructor <MODEL> cannot be invoked without 'new'.

I've found that by decorating the property with @Transform(({ value }) => (value.isInitialized() ? value.getItems() : undefined)) it is able to transform it correctly (basically, I'm forcing a plain array or undefined).

Proposed solution

In my humble opinion, class-transformer would benefit on having global type-based rules to transform certain types of data.

For example:

// class-transformer provided
interface Transformation<TClass extends object, TPlain = unknown> {
   toPlain(value: TClass): TPlain;
   toClass(value: TPlain): TClass;
}

// Custom project-based code
class ArrayCollectionTransformation implements Transformation<ArrayCollection> {
   public toPlain(value: ArrayCollection): unknown {
      return value.isInitialized() ? value.getItems() : undefined;
   }

   public toClass(value: unknown): ArrayCollection {
      throw new Error('To be implemented');
   }
}

const data = ...; // Some data with objects with properties with ArrayCollection as type
instanceToPlain(data, { transformationRules: { ArrayCollection: new ArrayCollectionTransformation()}});  // Not sure how to define the type to be effective, tho

Metadata

Metadata

Assignees

No one assigned

    Labels

    flag: needs discussionIssues which needs discussion before implementation.type: featureIssues related to new features.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions