Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping Entity-to-DTO (and vice-versa) in Nest.js

Tags:

dto

nestjs

I'm building an API with Nest.js and I've been using a mapper to convert the TypeORM entity to a DTO (and vice-versa).

Until now, I've been doing this manually:

 public static async entityToDto(entity: UserEntity): Promise<UserDto> {
    const dto = new UserDto();

    dto.id = entity.id;
    dto.emailAddress = entity.emailAddress;
    dto.firstName = entity.firstName;
    dto.lastName = entity.lastName;
    dto.addressLine1 = entity.addressLine1;
    dto.addressLine2 = entity.addressLine2;
    dto.townCity = entity.townCity;
 
    [...]

    return dto;
  }

In my opinion, this is a nice (albeit inflexible) approach. It explicitly controls which fields are returned to the user. However, I was under the impression that the purpose of a DTO is to have a single place to modify data about something. If I needed to add a field, I'd have to modify both the DTO and the mapper.

It seems to be the convention to have one mapper per entity. However, if I don't want to return, for example, the accountStatus field, I would have to write a new mapper. So I have now multiple mappers which would need to be modified.

I had the idea to write a "universal" mapper which looks at the fields in the DTO, and maps them to the fields in the entity.

I'm relatively new to TypeScript and Nest.js, so I was wondering how others manage this.

like image 239
Obvious_Grapefruit Avatar asked Oct 29 '25 07:10

Obvious_Grapefruit


1 Answers

I suggest you should try object property map built-in by typescript. Basically, your entity can be map to dto based on the similar property name like below

 public static async entityToDto(entity: UserEntity): Promise<UserDto> {
    const dto : UserDTO = ({
        ...entity,
        additionalProperty: entity.someProperty
    });

    return dto;
  }

Any property that sharing the same name between DTO and Entity will be mapped. It is far more clean and more flexible.

like image 103
Hoang Thinh Avatar answered Oct 31 '25 12:10

Hoang Thinh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!