Dto to entity and dto from entity

Viewed 9287

In my app I need multi times map from the Entity (Database model) to DTO (local object)

Most times, Dto have the same names as the entity

For example The Entity

export class CompanyModel extends BaseEntity {
  constructor(init?: Partial<CompanyModel>) {
  }
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ length: 500 })
  name: string;

  @Column({ length: 500, unique: true })
  email: string;




  ....

}

The DTO

export class Company {
  @ApiProperty()
  id: string;


  @ApiProperty()
  email: string;

  @ApiProperty()
  name: string;
...
}

Now I add static function toModel and fromModel

  static toModel(companyDto :CreateCompanyDto ) : CompanyModel {
    const companyModel =  new CompanyModel();

    const {name, email,..... } = companyDto;
    companyModel.name = name;
    companyModel.email =email
   
.....
    return companyModel;
}

What is the best solution for mapping DTO to ENTITY in nestjs / node

1 Answers

Well, it depend, what other things do you plan with your dtos. In my application I put a lot of pre- or post-processing on my dto-s. Here is an example, where I want to restrict the format of the email property:

export class Company {
  @ApiProperty()
  id: string;

  @ApiProperty()
  @Transform(value => value.toLowerCase())
  email: string;

  @ApiProperty()
  name: string;
...
}

If you plan to use these transformations, I suggest to use the class-transformer: classToPlain, plainToClass methods, so you can safely and effectively transform your data from the dto object to an entity instance. You can even put different transformations on both of your classes.

static toModel(companyDto: CreateCompanyDto ): CompanyModel {
  const data = classToPlain(companyDto);
  return plainToClass(CompanyModel, data);
}

You can find more information on the link I mentioned above. It can even help you, how to control the properties on your dtos or how to change their behaviour based on different use-cases.

Related