如何验证 nestjs dto 中的重复项?

How to validate duplicates in nestjs dto?

在 Nest js create dto 中,我收到两个属性名称和年龄。我需要通过 400 错误“重复值”验证具有姓名和年龄的用户是否已经存在。 就像在 table 中一样,我们有姓名:“John”,年龄:20 并且我们使用相同的 value/combination "John" 和 20 创建用户,它应该显示错误。 我尝试使用验证检查 NameExists 但不知道如何为两者取值,我只取一个。 https://dev.to/avantar/custom-validation-with-database-in-nestjs-gao

@IsNotEmpty({
    message: 'Name is missing',
  })
  @MinLength(5, {
    message: 'Name is too short. Select name longer than 5 characters.',
  })
  @UserExists()
  name: string;

@IsNotEmpty({
    message: 'Age is missing.',
  })
  @IsInt()
  @Transform(({ value }) => Number(value))
  age: number;

在此示例中,您可以了解如何在自定义装饰器中访问对象的其他属性。 https://github.com/typestack/class-validator#custom-validation-decorators

但是,在这种情况下,我的选择是在数据库中创建适当的唯一索引并处理数据库错误,因为如果 2 个请求同时具有相同的用户名和年龄,您可能会遇到竞争条件时间.