NodeJS map Dtos to TypeORM Entities

Aaron Ullal picture Aaron Ullal · Jun 30, 2018 · Viewed 7.3k times · Source

I have a nodejs REST API backend running the nestjs framework, using typeORM as ORM for my entities.

Coming from a C#/Entity Framework background, I am very used to have my Dtos mapped to the database entities.

Is there a similar approach with typeORM?

I have seen the automapper-ts library, but those magic strings in the map declarations look kind of scary... Basically it would be amazing if I could :

let user: TypeORMUserEntity = mapper.map<TypeORMUserEntity>(userDto);

What is the way to do this (or any alternative with same result) in nodejs/typeorm backend environment?

Answer

Alexey Petushkov picture Alexey Petushkov · Jun 30, 2018

You can use class-transformer library. You can use it with class-validator to cast and validate POST parameters.

Example:

@Exclude()
class SkillNewDto {
  @Expose()
  @ApiModelProperty({ required: true })
  @IsString()
  @MaxLength(60)
  name: string;

  @Expose()
  @ApiModelProperty({
    required: true,
    type: Number,
    isArray: true,
  })
  @IsArray()
  @IsInt({ each: true })
  @IsOptional()
  categories: number[];
}

Exclude and Expose here are from class-transform to avoid additional fields.

IsString, IsArray, IsOptional, IsInt, MaxLength are from class-validator.

ApiModelProperty is for Swagger documentation

And then

const skillDto = plainToClass(SkillNewDto, body);
const errors = await validate(skillDto);
if (errors.length) {
  throw new BadRequestException('Invalid skill', this.modelHelper.modelErrorsToReadable(errors));
}