NodeJS 将 Dto 映射到 TypeORM 实体

问题描述 投票:0回答:3

我有一个运行

nodejs
框架的
nestjs
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
3个回答
7
投票

您可以使用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[];
}
这里的

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

2
投票

我正在使用

create
 中的 
getRepository

方法

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

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

0
投票

您可以使用数据转换对象。

这是示例:

class LoginResDto {
 token?: string;

 addCustomProperty = (propertyName: AllowedKeys, propertyValue: any): this => {
   this[propertyName] = propertyValue;
   return this;
 };

 @Expose()
 type: UserType;

 @Expose()
 name: string;

 @Expose()
 surname: string;

 @Expose()
 publicId: number;

 @Expose({
   name: 'I',
 })
 @Type(() => HumanResDto)
 detail: HumanResDto;
}

export default LoginResDto;

通话功能:

const convertData = TransformService.convert<LoginResDto, UserEntity>(
           userExist,
           LoginResDto,
           'excludeAll'
         ).addCustomProperty('token', tokenInstance.clientToken);

转换服务:

class TransformService {
  static convert<T, K>(
    source: K,
    destinationClass: ClassConstructor<T>,
    strategy: 'excludeAll' | 'exposeAll'
  ): T {
    return plainToClass(destinationClass, source, { strategy });
  }

  static convertArray<T, K>(
    source: K[],
    destinationClass: ClassConstructor<T>,
    strategy: 'excludeAll' | 'exposeAll'
  ): T[] {
    return plainToInstance(destinationClass, source, { strategy });
  }
}

export default TransformService;
© www.soinside.com 2019 - 2024. All rights reserved.