你可以用
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
是为了虚张声势的文件
然后
const skillDto = plainToClass(SkillNewDto, body);
const errors = await validate(skillDto);
if (errors.length) {
throw new BadRequestException('Invalid skill', this.modelHelper.modelErrorsToReadable(errors));
}