【问题标题】:How can I filter out excess model property如何过滤掉多余的模型属性
【发布时间】:2018-10-19 02:07:47
【问题描述】:

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

export class CreateProductDTO {
  readonly _id: number;
  readonly _name: string;
  readonly _price: number;
}

DTO 在我的 post 方法中使用

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

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

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

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

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

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

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

【问题讨论】:

    标签: node.js typescript nestjs


    【解决方案1】:

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

    new ValidationPipe({whitelist: true})
    

    如果您希望在存在任何未列入白名单的属性时引发错误:

    new ValidationPipe({whitelist: true, forbidNonWhitelisted: true})
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多