NodeJS 将 Dtos 映射到 TypeORM 实体

NodeJS map Dtos to TypeORM Entities

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

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

typeORM 有类似的方法吗?

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

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

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

您可以使用 class-transformer library. You can use it with 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));
}

我正在使用 getRepository

中的 create 方法

export async function save(booking: createBookingDto) {
  const bookingRepository = getRepository(Booking);

  const bookingEntity = bookingRepository.create({ ...booking });
  return bookingRepository.save(bookingEntity);
}