class-transformer icon indicating copy to clipboard operation
class-transformer copied to clipboard

feature: support global type-based rules

Open carlosV2 opened this issue 2 years ago • 2 comments

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

carlosV2 avatar Apr 13 '22 16:04 carlosV2

+1

vsinghipcium avatar Aug 30 '22 22:08 vsinghipcium

+1

kotoyama avatar Feb 01 '24 03:02 kotoyama