如何过滤掉多余的模型属性

Lux*_*rot 2 node.js typescript nestjs

我有一个像这样的 DTO 对象:

export class CreateProductDTO {
  readonly _id: number;
  readonly _name: string;
  readonly _price: number;
}
Run Code Online (Sandbox Code Playgroud)

我的 post 方法中使用了 DTO

@Post('users')
async addUser(@Response() res, @Body(new ValidationPipe()) createUserDTO: CreateUserDTO) {
    await this.userService.addUser(createUserDTO).subscribe((users) => {
        res.status(HttpStatus.OK).json(users);
    });
}
Run Code Online (Sandbox Code Playgroud)

当我发布 json 数据时,它将序列化为 CreateProduceDTO obcjet

{
  "_id":1,
  "_name":"Lux",
  "_age":19
}
Run Code Online (Sandbox Code Playgroud)

但我发布带有多余属性的 json 数据,它也序列化为带有多余属性的 CreateProduceDTO obcjet

{
  "_id":1,
  "_name":"Lux",
  "_age":19,
  "test":"abcv"
}

CreateUserDTO { _id: 1, _name: 'Lux', _age: 19, test: 'abcv' }
Run Code Online (Sandbox Code Playgroud)

我曾尝试用管道过滤它,但我不知道。谢谢大家。

Val*_*era 7

如果您只想删除多余的属性,可以像这样使用 ValidationPipe :

new ValidationPipe({whitelist: true})
Run Code Online (Sandbox Code Playgroud)

如果您希望在存在任何非白名单属性时抛出错误:

new ValidationPipe({whitelist: true, forbidNonWhitelisted: true})
Run Code Online (Sandbox Code Playgroud)

查看https://www.npmjs.com/package/class-validator#whitelisting了解更多选项