NestJS Swagger中如何直接验证请求体传入的UUID数组
解决方案
针对请求体直接传入UUID数组的校验需求,以下是两种可直接落地的实现方案:
方案1:自定义校验管道(兼容性最优,支持Swagger、自定义规则)
该方案适配所有Nest版本,支持自定义错误提示、额外校验规则,也能完美对接Swagger文档生成。
步骤1:创建UUID数组专用校验管道
// uuid-array.pipe.ts import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common'; import { validate } from 'class-validator'; import { plainToInstance } from 'class-transformer'; import { IsUUID } from 'class-validator'; import { ApiProperty } from '@nestjs/swagger'; // 内部校验用DTO class UuidArrayDto { @IsUUID('4', { each: true, message: '存在不符合UUIDv4格式的参数' }) @ApiProperty({ type: [String], example: ['9322c384-fd8e-4a13-80cd-1cbd1ef95ba8', '986dcaf4-c1ea-4218-b6b4-e4fd95a3c28e'] }) uuids: string[]; } @Injectable() export class UuidArrayValidationPipe implements PipeTransform { async transform(value: any) { // 先校验请求体是否为数组 if (!Array.isArray(value)) { throw new BadRequestException('请求体必须为UUID数组格式'); } // 转换为DTO结构执行校验 const dtoInstance = plainToInstance(UuidArrayDto, { uuids: value }); const errors = await validate(dtoInstance); if (errors.length > 0) { const errorMsg = errors.map(item => Object.values(item.constraints)).flat().join(';'); throw new BadRequestException(errorMsg); } // 校验通过直接返回原数组 return value; } }
步骤2:控制器中直接使用
// 控制器代码 import { Controller, Post, Body } from '@nestjs/common'; import { ApiBody } from '@nestjs/swagger'; import { UuidArrayValidationPipe } from './uuid-array.pipe'; @Post('your-endpoint') // 配置Swagger请求体说明 @ApiBody({ type: [String], example: ['9322c384-fd8e-4a13-80cd-1cbd1ef95ba8', '986dcaf4-c1ea-4218-b6b4-e4fd95a3c28e'] }) public getIds( @Body(UuidArrayValidationPipe) uuids: string[] ) { // 此处拿到的uuids已经是全部校验通过的UUIDv4数组 console.log(uuids); }
方案2:内置ParseArrayPipe实现(轻量无额外文件)
如果不需要复杂自定义规则,可直接使用Nest内置管道快速实现,代码更简洁:
import { Controller, Post, Body, ParseArrayPipe, BadRequestException } from '@nestjs/common'; import { IsUUID } from 'class-validator'; import { ApiBody } from '@nestjs/swagger'; @Post('your-endpoint') @ApiBody({ type: [String], example: ['9322c384-fd8e-4a13-80cd-1cbd1ef95ba8', '986dcaf4-c1ea-4218-b6b4-e4fd95a3c28e'] }) public getIds( @Body( new ParseArrayPipe({ items: String, validate: true, exceptionFactory: () => new BadRequestException('存在无效的UUIDv4参数'), validatorOptions: { each: true, constraints: ['4'], }, }), ) @IsUUID('4', { each: true }) uuids: string[], ) { console.log(uuids); }
内容的提问来源于stack exchange,提问作者MOE
相关产品推荐
相关产品推荐

