Swagger/NestJS中如何编写DTO实现对象数组的参数校验
解决方案
你现有的DTO定义适配的是请求体为外层带tags字段的对象结构,和你需要校验的「请求体直接为对象数组」的场景不匹配,调整方式如下:
第一步:保留原有Tags类
你写的Tags类的字段校验规则完全符合需求,不用修改:
export class Tags { @ApiProperty({ description: 'The name of the tag', example: 'Tag 1', required: true }) @IsString() @MaxLength(30) @MinLength(1) name: string; @ApiProperty({ description: 'The description of the tag', example: 'This is the first tag', required: true }) @IsString() @MinLength(3) description: string; }
第二步:调整接口参数接收逻辑
不需要再定义外层的CreateTagDto,直接在Controller的接口参数中使用ParseArrayPipe绑定Tags类做校验即可,代码示例:
import { Controller, Post, Body, ParseArrayPipe } from '@nestjs/common'; import { Tags } from './tags.dto'; @Controller('tags') export class TagsController { @Post() batchCreateTags( @Body(new ParseArrayPipe({ items: Tags, whitelist: true })) tags: Tags[] ) { // 此处拿到的tags就是已经校验通过的合规数组 return tags; } }
可选:添加数组全局校验规则
如果需要限制数组最少1项、最多100项这类全局规则,可以在ParseArrayPipe的配置中添加对应参数:
@Body(new ParseArrayPipe({ items: Tags, whitelist: true, minLength: 1, maxLength: 100 }))
依赖确认
确保项目已经安装了两个必需依赖,否则校验规则不会生效:
npm install class-validator class-transformer
内容的提问来源于stack exchange,提问作者t97
相关产品推荐
相关产品推荐

