如何在Nest.js DTO中传递含单个元素的数组?
Nest.js中Query单值数组无法被DTO解析为数组的解决方案
问题根源
你的代码里DTO的@Transform装饰器未生效,核心原因是@Query()默认不会触发class-transformer的类型转换逻辑,只有配置ValidationPipe并开启transform选项时,才会执行DTO中的转换规则。另外,DTO中urlList的类型定义有误([]应改为string[])。
修复步骤
1. 修正DTO的类型定义
把urlList的类型从空数组[]改为明确的string[],保证类型校验精准:
export class DownloadDocsDto { @Transform(({ value }) => Array.isArray(value) ? value : [value]) @IsNotEmpty() @IsArray() @IsString({ each: true }) @ApiProperty({ example: ['test.pdf'], description: 'Document Url List', required: true, }) public urlList: string[]; // 修正为string[]类型 }
2. 在控制器中启用ValidationPipe
在@Query()装饰器中传入ValidationPipe并开启transform选项,触发DTO的转换逻辑:
import { ValidationPipe } from '@nestjs/common'; @Get('/download/docs') @ApiOperation({ summary: 'Download documents' }) async downloadDocs(@Query(new ValidationPipe({ transform: true })) urlList: DownloadDocsDto) { console.log(urlList); // 单个值会被转为数组格式 }
3. (可选)全局配置ValidationPipe
如果想让整个项目都自动启用类型转换和校验,可在main.ts中全局注册ValidationPipe:
async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalPipes(new ValidationPipe({ transform: true })); await app.listen(3000); } bootstrap();
全局配置后,控制器方法无需单独传入ValidationPipe,就能自动触发DTO的转换和校验。
验证结果
- 传递单个参数:
GET /download/docs?urlList=test.pdf,输出为{ urlList: ['test.pdf'] } - 传递多个参数:
GET /download/docs?urlList=test1.pdf&urlList=test2.pdf,输出为{ urlList: ['test1.pdf', 'test2.pdf'] }
内容的提问来源于stack exchange,提问作者Code The World
相关产品推荐
相关产品推荐

