Reputation: 1758
I am trying to do a Transformation of an input object to a Dto.
//input object
const input = {
"steps": [{ "id": 1}, {"id": 2}],
"foo": "bar",
"currentStep": {"id": 1}
}
So I have created those DTO classes
import { Expose, Transform, Type } from 'class-transformer';
export class StepDTO {
@Expose()
@Transform(({ obj }) => obj.id)
transformedFoo: number;
}
export class MainDTO {
@Expose()
@Transform(({ obj }) => obj.foo)
transformedFoo: number;
@Expose()
@Transform(({ obj }) => obj.steps)
@Type(() => StepDTO)
updatedSteps: StepDTO[];
@Expose()
@Transform(({ obj }) => obj.steps[0])
@Type(() => StepDTO)
currentStep: StepDTO;
}
const transformed = plainToInstance(
MainDTO,
input,
{
excludeExtraneousValues: true,
},
);
But unfortunately, the result looks like this
{"transformedFoo":"bar","updatedSteps":[{"id":1,"test":"1"},{"id":2,"test":"2"}],"currentStep":{"id":1,"test":"1"}}
It is perfectly working on the main DTO but not onto the nested ones.
I found a solution which does not sound optimal to me by replacing the updatedSteps transform by
@Expose()
@Transform(({ obj }) =>
plainToInstance(StepDTO, obj.steps, { excludeExtraneousValues: true })
)
@Type(() => StepDTO)
updatedSteps: StepDTO[];
Any better idea?
Here's a codesandbox showing the issue https://codesandbox.io/p/devbox/class-transformer-forked-jtkm9n?workspaceId=ws_FXWvFqR2ZwREcHThAQPtQx
Thanks in advance!
Upvotes: 1
Views: 14