class-transformer
class-transformer copied to clipboard
feature: support global type-based rules
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
+1
+1