NodeJS 将 Dtos 映射到 TypeORM 实体

Aar*_*lal 7 dto node.js typeorm nestjs class-transformer

我有一个nodejs运行nestjs框架的REST API 后端,使用typeORM作为我的实体的ORM

来自C#/Entity Framework背景,我非常习惯将我的 Dtos 映射到数据库实体。

typeORM 是否有类似的方法?

我看过automapper-ts库,但是地图声明中的那些魔法字符串看起来有点吓人......基本上,如果我能:

let user: TypeORMUserEntity = mapper.map<TypeORMUserEntity>(userDto);
Run Code Online (Sandbox Code Playgroud)

在 nodejs/typeorm 后端环境中执行此操作的方法是什么(或任何具有相同结果的替代方法)?

小智 7

您可以使用类转换器库。您可以将它与类验证器一起使用来转换和验证 POST 参数。

例子:

@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[];
}
Run Code Online (Sandbox Code Playgroud)

ExcludeExpose这里距离class-transform以避免额外的字段。

IsString, IsArray, IsOptional, IsInt,MaxLength来自class-validator

ApiModelProperty 用于 Swagger 文档

进而

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

  • 这不是 DTO -&gt; DTO 而不是 DTO -&gt; 实体映射吗?```typescript const SkillDto = plainToClass(SkillNewDto, body); ```` (6认同)