Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

serialize nested objects using class-transformer : Nest js

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:'[email protected]',
    first_name: 'test',
    last_name: 'test',
    profile: {
        date_of_birth: '',
        address: '',
        pincode: ''
    }
}
like image 242
RAHUL KUNDU Avatar asked Mar 22 '26 14:03

RAHUL KUNDU


1 Answers

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
    
});
like image 74
RAHUL KUNDU Avatar answered Mar 24 '26 05:03

RAHUL KUNDU