【问题标题】:validating an array of uuids in nestjs swagger body验证nestjs swagger body中的uuid数组
【发布时间】:2022-01-09 21:52:46
【问题描述】:

这听起来像是一个非常简单的问题,但我一直在寻找解决方案很长时间了。我想验证端点中的一组 UUID。

像这样: ["9322c384-fd8e-4a13-80cd-1cbd1ef95ba8", "986dcaf4-c1ea-4218-b6b4-e4fd95a3c28e"]

我已经成功地将它实现为 JSON 对象{ "id": ["9322c384-fd8e-4a13-80cd-1cbd1ef95ba8", "986dcaf4-c1ea-4218-b6b4-e4fd95a3c28e"]},代码如下:

public getIds(
  @Body(ValidationPipe)
  uuids: uuidDto
) {
  console.log(uuids);
}
import { ApiProperty } from '@nestjs/swagger';
import { IsUUID } from 'class-validator';

export class uuidDto {
  @IsUUID('4', { each: true })
  @ApiProperty({
    type: [String],
    example: [
      '9322c384-fd8e-4a13-80cd-1cbd1ef95ba8',
      '986dcaf4-c1ea-4218-b6b4-e4fd95a3c28e',
    ],
  })
  id!: string;
}

但不幸的是,我无法自定义调用该端点的函数。所以我需要一个解决方案来只验证一组 uuid。

【问题讨论】:

    标签: nestjs class-validator nestjs-swagger


    【解决方案1】:

    而不是类型字符串,写字符串[]。如下:

    import { ApiProperty } from '@nestjs/swagger';
    import { IsUUID } from 'class-validator';
    
    export class uuidDto {
      @IsUUID('4', { each: true })
      @ApiProperty({
        type: string[],
        example: [
          '9322c384-fd8e-4a13-80cd-1cbd1ef95ba8',
          '986dcaf4-c1ea-4218-b6b4-e4fd95a3c28e',
        ],
      })
      id!: string[];
    }
    

    【讨论】:

    • 但是问题仍然存在,我有一个具有属性 id 的对象,它是一个数组,我只想拥有一个不需要 id 属性的数组
    • 所以我猜 DTO 方法是错误的,因为我没有对象
    • 是的,您不需要对象,但如果您认为需要,只需为其创建一个接口并将其导出,然后在您的 dto 中使用它
    【解决方案2】:

    你可以为它建立一个custom validation pipe

    @Injectable()
    export class CustomClassValidatorArrayPipe implements PipeTransform {
    
      constructor(private classValidatorFunction: (any)) {}
    
      transform(value: any[], metadata: ArgumentMetadata) {
        const errors = value.reduce((result, value, index) => {
          if (!this.classValidatorFunction(value))
            result.push(`${value} at index ${index} failed validation`)
          return result
        }, [])
    
        if (errors.length > 0) {
          throw new BadRequestException({
            status: HttpStatus.BAD_REQUEST,
            message: 'Validation failed',
            errors
          });
        }
    
        return value;
      }
    }
    

    在您的控制器中:

    @Post()
    createExample(@Body(new CustomClassValidatorArrayPipe(isUUID)) body: string[]) {
      ...
    }
    
    • 确保使用 class-validator 中的小写函数。它必须是 isUUID 而不是 IsUUID。 (这用于manual validation with class-validator。)
    • CustomClassValidatorArrayPipe 是模块化构建。您可以使用它验证任何其他类型。例如MongoId@Body(new CustomClassValidatorArrayPipe(isMongoId)) body: ObjectId[]

    结果

    如果你发送这个:

    POST http://localhost:3000/example
    Content-Type: application/json
    
    [
      "986dcaf4-c1ea-4218-b6b4-e4fd95a3c28e",
      "123",
      "test"
    ]
    

    服务器会回复:

    {
      "status": 400,
      "message": "Validation failed",
      "errors": [
        "123 at index 1 failed validation",
        "test at index 2 failed validation"
      ]
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-05
      • 2019-10-09
      • 2020-04-11
      • 2021-01-29
      • 1970-01-01
      • 2021-11-17
      • 2020-08-29
      • 2020-08-06
      • 2021-03-09
      相关资源
      最近更新 更多