首页 文章

NodeJS将Dtos映射到TypeORM实体

提问于
浏览
2

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

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

是否有类似的方法与typeORM?

我见过automapper-ts库,但是 Map 声明中的那些神奇的字符串看起来有些可怕......基本上如果我可以:

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

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

1 回答

  • 2

    您可以使用class-transformer库 . 您可以将它与class-validator一起使用来转换和验证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[];
    }
    

    ExcludeExpose 这里来自 class-transform 以避免其他字段 .

    IsStringIsArrayIsOptionalIsIntMaxLength 来自 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));
    }
    

相关问题