16

创建新用户将忽略未指定的对象create-user.dto.ts

但是,当我更新用户时,它会添加不需要的字段,如下所示:

// update-user.dto.ts
import { IsEmail } from 'class-validator';
import { Address } from '../model/address';

export class UpdateUserDto {
  firstName: string;

  lastName: string;

  @IsEmail(undefined, { message: 'Not a valid e-mail' })
  email: string;

  username: string;

  password: string;

  addresses: Address[];
}

这是来自用户服务的更新操作

// user.service.ts
  async update(data: UpdateUserDto) {
    try {
      this.logger.log(data);
      const id = '5c6dd9852d4f441638c2df86';
      const user = await this.userRepository.update(id, data);

      return { message: 'Updated your information' };
    } catch (error) {
      this.logger.log(error);
      throw new HttpException('', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

这是 user.controller.ts

  @Patch()
  @UsePipes(CustomValidationPipe)
  async update(@Body() data: UpdateUserDto) {
    return this.userService.update(data);
  }

客户端补丁数据:

// Unwanted junk from client
{
  "email": "newemail@gmail.com",
  "junk": "junk"
}

email正确更新,但该行将有一个新的不需要的属性junk,其值为junk

4

3 回答 3

15

我假设你在你class-transformer的.validateCustomValidationPipe

当您将whitelist选项传递给它时,validate将删除所有未知(-> DTO 类中没有注释)属性:

validate(userUpdate, { whitelist: true })

如果您想抛出验证错误而不是仅仅剥离未知属性,您可以另外传递该forbidNonWhitelisted选项。

validate(userUpdate, { whitelist: true, forbidNonWhitelisted: true });

在更新的情况下,您可能还想使用skipMissingProperties: true,这样 validate 就不会抛出错误,例如当lastName不是更新的一部分时。


请注意,您应该注释 dto 类中的所有属性,以使验证正常工作:

@IsString()
lastName: string;

@ValidateNested()
@Type(() => Address)
address: Address
于 2019-02-21T18:59:25.850 回答
7

不确定何时将此行为/选项添加到 NestJS(可能是在原始问题和接受的答案之后添加的),但实现未知属性剥离的最佳方法是:

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

这就对了。只要确保你有whitelist: true你的配置,你就不会得到任何未知/无效的属性。

您还可以通过设置另一个名为forbidNonWhitelistedto的属性来完全停止请求true

更多信息在这里:https ://docs.nestjs.com/techniques/validation#stripping-properties

于 2020-12-08T10:20:13.083 回答
-1

我找到了解决方案:

这就是 user.service.ts update() 的样子:

const user = await this.userRepository.create(data);

需要在之前添加

await this.userRepository.update(id, user);

这是完整的 user.service.ts update()

  async update(data: UpdateUserDto) {
    this.logger.log(data);

    // added for testing purposes (id should be based on active user)
    const id = '5c6ef2c823bf4e3414d65cd0';
    const user = await this.userRepository.create(data);
    await this.userRepository.update(id, user);

    return { message: 'Updated your information' };
  }

现在任何不需要的属性都不会添加到行中

于 2019-02-21T18:55:27.360 回答