NodeJS map Dtos to TypeORM Entities

Multi tool use
NodeJS map Dtos to TypeORM Entities
I have a nodejs
REST API backend running the nestjs
framework, using typeORM as ORM for my entities.
nodejs
nestjs
Coming from a C#/Entity Framework
background, I am very used to have my Dtos mapped to the database entities.
C#/Entity Framework
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?
1 Answer
1
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.
Exclude
Expose
class-transform
IsString
, IsArray
, IsOptional
, IsInt
, MaxLength
are from class-validator
.
IsString
IsArray
IsOptional
IsInt
MaxLength
class-validator
ApiModelProperty
is for Swagger documentation
ApiModelProperty
And then
const skillDto = plainToClass(SkillNewDto, body);
const errors = await validate(skillDto);
if (errors.length) {
throw new BadRequestException('Invalid skill', this.modelHelper.modelErrorsToReadable(errors));
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.