You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS+Swagger:如何将ApiProperty配置为逗号分隔的字符串列表

实现逗号分隔的数组查询参数(NestJS Swagger 7.3.1)

完全可以实现,核心思路是将DTO中字段类型改为字符串,配合自定义解析逻辑把逗号分隔值转成数组,同时调整Swagger注解让UI显示正确的输入控件。具体步骤如下:

1. 修改DTO的Swagger注解与字段定义

把原来的数组类型字段改为字符串,通过@ApiProperty明确标注为字符串类型,并补充格式说明:

import { ApiProperty } from '@nestjs/swagger';
import { IsString } from 'class-validator';

export class YourQueryDto {
  @ApiProperty({
    type: String,
    description: '多个值用逗号分隔,示例:item1,item2',
    example: 'item1,item2',
  })
  @IsString() // 确保传入的是字符串格式
  type: string;
}

2. 实现逗号分隔值的解析逻辑

有两种实现方式,选其一即可:

方式一:自定义管道解析

创建管道处理字符串到数组的转换,同时处理空值、无效格式等边界情况:

import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';

@Injectable()
export class SplitPipe implements PipeTransform {
  transform(value: string): string[] {
    if (!value) return []; // 无参数时返回空数组,可按需调整
    // 分割后去除每个值的前后空格,过滤空字符串
    const validValues = value.split(',').map(item => item.trim()).filter(item => item);
    if (validValues.length === 0) {
      throw new BadRequestException('type参数格式错误,需提供有效逗号分隔值');
    }
    return validValues;
  }
}

在控制器中使用管道:

import { Controller, Get, Query } from '@nestjs/common';
import { SplitPipe } from './pipes/split.pipe';

@Controller('your-resource')
export class YourController {
  @Get()
  findAll(@Query('type', SplitPipe) type: string[]) {
    // 此时type已经是解析后的字符串数组,直接使用即可
    return { filters: { type } };
  }
}

方式二:用class-transformer直接在DTO处理

无需单独创建管道,通过@Transform装饰器在DTO内完成解析:

import { ApiProperty } from '@nestjs/swagger';
import { IsString } from 'class-validator';
import { Transform } from 'class-transformer';

export class YourQueryDto {
  @ApiProperty({
    type: String,
    description: '多个值用逗号分隔,示例:item1,item2',
    example: 'item1,item2',
  })
  @IsString()
  @Transform(({ value }) => value.split(',').map(item => item.trim()).filter(Boolean))
  type: string[];
}

控制器直接接收DTO:

import { Controller, Get, Query } from '@nestjs/common';
import { YourQueryDto } from './dto/your-query.dto';

@Controller('your-resource')
export class YourController {
  @Get()
  findAll(@Query() query: YourQueryDto) {
    // query.type 已转为字符串数组
    return { filters: query.type };
  }
}

效果验证

  • Swagger UI会显示单个文本输入框,提示用户输入逗号分隔的内容
  • 前端请求格式为...?type=item1,item2
  • 后端直接拿到解析后的字符串数组,无需额外处理

内容的提问来源于stack exchange,提问作者Christian Benseler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 09:40:08