【问题标题】:NodeJS map Dtos to TypeORM EntitiesNodeJS 将 Dtos 映射到 TypeORM 实体
【发布时间】:2018-12-09 08:14:48
【问题描述】:

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

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

typeORM 有类似的方法吗?

我看过automapper-ts 库,但是地图声明中的那些魔法字符串看起来有点吓人…… 基本上,如果可以的话,那就太棒了:

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

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

【问题讨论】:

    标签: node.js dto nestjs typeorm class-transformer


    【解决方案1】:

    我正在使用来自getRepositorycreate 方法

    
    export async function save(booking: createBookingDto) {
      const bookingRepository = getRepository(Booking);
    
      const bookingEntity = bookingRepository.create({ ...booking });
      return bookingRepository.save(bookingEntity);
    }
    

    【讨论】:

      【解决方案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));
      }
      

      【讨论】:

      • 这不是 DTO -> DTO 而不是 DTO -> 实体映射吗? typescript const skillDto = plainToClass(SkillNewDto, body);
      猜你喜欢
      • 2020-08-05
      • 2020-04-06
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-27
      • 1970-01-01
      相关资源
      最近更新 更多