Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform class to class/object (Entity to DTO) in TypeScript and NestS

How to transform database entity User:

class User {
  public firstName: string;
  public lastName: string;
  public phone?: string;
  public email: string;
  public status: EUserState;
  public tokens: Token[];
  public password: string;
}

into DTO entity GetUserDTO:

class GetUserDTO {
  public id: number;
  public firstName: string;
  public lastName: string;
  public phone?: string;
  public email: string;
}

in TypeScript? I am using @nestjs, class-validator and class-transformer packages, but I not found any way to use them to achieve this.

Somebody can say, that having DTO is pointless for this, but we have DTOs shared between server and client to maintain API structure.

Any ideas?

like image 235
Baterka Avatar asked Feb 09 '20 18:02

Baterka


1 Answers

There are couple of ways to achieve what you want

  1. You can manually map from Domain models to DTOs using static function from either the Domain or DTO
export class Domain {
   ...
   static toDTO(domain: Domain) {
      // mapping goes here
   }
}

or

export class Dto {
   ...
   static fromDomain(domain: Domain) {
      // mapping goes here
   }
}
  1. You can use a 3rd party library: automapper-ts, @wufe/mapper, @nartc/automapper (my lib), or morphism

class-transformer can also be considered a mapper, however, if you want to map from 1 model to another, then class-transformer can't really do that.

like image 102
Chau Tran Avatar answered Sep 20 '22 16:09

Chau Tran