使用管道将所有请求主体转换为没有冗余属性的DTO对象

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

我是 NestJs 的新手。我想对传入请求进行转换,以删除未在 DTO 文件中声明的冗余属性。

我有DTO:

export class UpdateUserDto {
  @Expose() id: string

  @Expose() name: string

  @Expose() address: string

  @Expose() phone: string
}

控制器:

@Patch(':id')
async update(@Param('id') id: string, @Body() updateData: UpdateUserDto): Promise<UserEntity> {
  return await this.userService.update(id, updateData)
}

传入请求正文:

{
  "id": "123",
  "name": "Name test",
  "address": "Address test",
  "phone": "12312312",
  "hahaha": "hihihi" // this property not declare in DTO file will be remove
}

我要转车到

{
  "id": "123",
  "name": "Name test",
  "address": "Address test",
  "phone": "12312312"
}

我可以用Custom Pipe来处理吗。像这样:

控制器:

@Patch(':id')
@UsePipes(new RequestTransferPipe(UpdateUserDto))
async update(@Param('id') id: string, @Body() updateData: UpdateUserDto): Promise<UserEntity> {
  return await this.userService.update(id, updateData)
}

我试图从 ArgumentMetadata 获取元类型,但传入请求已转移到空对象。我想保留在 DTO 文件中声明的属性并删除其他属性

nestjs pipe dto class-transformer
1个回答
0
投票

所有类验证器选项(继承自 ValidatorOptions 接口)都可用: ... whitelist |布尔 |如果设置为 true,验证器将抛出异常,而不是剥离非白名单属性。

app.useGlobalPipes(new ValidationPipe({
  whitelist: true
}));

文档

© www.soinside.com 2019 - 2024. All rights reserved.