问题描述
我有一个 nodejs
REST API后端,它使用 typeORM 运行 nestjs
框架为我的实体的 ORM 。
I have a nodejs
REST API backend running the nestjs
framework, using typeORM as ORM for my entities.
来自 C#/ Entity Framework
背景,我很习惯将Dto映射到数据库实体。
Coming from a C#/Entity Framework
background, I am very used to have my Dtos mapped to the database entities.
typeORM是否有类似的方法?
Is there a similar approach with typeORM?
我见过库,但是地图声明中的那些魔术字符串看起来有些吓人...
如果可以的话,这基本上是令人惊讶的:
I have seen the automapper-ts library, but those magic strings in the map declarations look kind of scary...Basically it would be amazing if I could :
let user: TypeORMUserEntity = mapper.map<TypeORMUserEntity>(userDto);
在nodejs / typeorm后端环境中执行此操作(或具有相同结果的任何替代方法)的方式是什么?
What is the way to do this (or any alternative with same result) in nodejs/typeorm backend environment?
推荐答案
您可以使用库。您可以将其与一起使用,以强制转换和验证POST参数。
You can use class-transformer library. You can use it with class-validator to cast and validate POST parameters.
示例:
@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[];
}
排除
和暴露
此处来自 class-transform
,以避免附加字段。
Exclude
and Expose
here are from class-transform
to avoid additional fields.
IsString
, IsArray
, IsOptional
, IsInt
, MaxLength
来自 class-validator
。
ApiModelProperty
用于Swagger文档
ApiModelProperty
is for Swagger documentation
然后
const skillDto = plainToClass(SkillNewDto, body);
const errors = await validate(skillDto);
if (errors.length) {
throw new BadRequestException('Invalid skill', this.modelHelper.modelErrorsToReadable(errors));
}
这篇关于NodeJS将Dto映射到TypeORM实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!