I am trying to serialize nested objects using a class transformer. I have two dtos like below. When I am trying to serialize using plainToClass
the nested object gets removed from the output. only getting the parent object's data.
User dto:
export class UserDto extends AbstractDto {
@Expose()
email: string;
@Expose()
first_name: string;
@Expose()
last_name: string;
@Expose()
profile: ProfileDto
}
Profile dto:
export class ProfileDto extends AbstractDto {
@Expose()
date_of_birth: string;
@Expose()
address: string;
@Expose()
pincode: string;
}
Serializer:
const serialized = plainToClass(UserDto, user, {
excludeExtraneousValues: true,
});
Expected Output:
{
email:'a@gmail.com',
first_name: 'test',
last_name: 'test',
profile: {
date_of_birth: '',
address: '',
pincode: ''
}
}
I have found the answer here Link. If I add enableImplicitConversion: true
along with the @Type
decorator then it is working as expected.
export class UserDto extends AbstractDto {
@Expose()
email: string;
@Expose()
first_name: string;
@Expose()
last_name: string;
@Expose()
@Type(() => ProfileDto)
profile: ProfileDto
}
Serializer:
const serialized = plainToClass(UserDto, user, {
excludeExtraneousValues: true,
enableImplicitConversion: true
});