'map multiple properties to single nested object using typescript and class-transformer
I'm using class-transformer (in nestjs) to convert my database entities into dto types to output from my api.
My database entities look like:
class MyEntity {
id: string;
property1: string;
property2: string;
}
but my API needs to output something like
class NestedDto {
property1: string;
property2: string;
}
class MyDto {
id: string;
nested: NestedDto;
}
So, using class-transformer, how do I combine those two properties into a single nested object?
I've tried using @Transform like this:
class MyDto {
@Expose()
id: string;
@Transform(p => ( property1: p.obj.property1, property2: p.obj.property2 }));
nested: any;
}
it technically works, but it doesn't scale and isn't very clean.
Is there a nicer way to achieve this using class-transformer?
Also, for bonus points, if those two properties are null in the database, it would be nice for the nested property on the api to not exist - though this is nice-to-have, and not a requirement :)
Solution 1:[1]
class MyDto {
@Expose()
id: string;
@Transform((p: MyEntity) => ( property1: p.obj.property1, property2: p.obj.property2 }));
@IsOptional()
nested: NestedDto;
}
YOLO I never used nestjs
Solution 2:[2]
@Transform(({ value, obj }) => {
value = new Card();
value.expiration = obj.expiryDate;
return value;}) productForeignCard: Card;
try this
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | GaspardF |
| Solution 2 | Ramil Memmedov |
