如何移除Swagger UI下拉列表中的"--"默认选项
移除Swagger UI下拉列表中的"--"空选项(NestJS场景)
我需要移除Swagger UI表单里下拉列表的默认"--"空选项,当前的NestJS接口代码如下,表单中FileModule、FileType、FileCategory这几个下拉框都存在该空选项:
@Post('upload') @ApiConsumes('multipart/form-data') @ApiBody({ required: true, schema: { type: 'object', properties: { FileModule:{type:'string', enum:[FileModule.GEOXING, FileModule.common], description: "Choose Module to Upload"}, FileType:{type:'string', enum:[FileType.IMG, FileType.DOC, FileType.XML], description: "Choose type of file to Upload" }, FileCategory:{type:'string', enum:[FileCategory.SITE, FileCategory.EXHIBITOR, FileCategory.SERVICE], description: "Choose category to upload"}, file: { type: 'string', format: 'binary', }, }, }, }) @UseInterceptors(FileExtender) @UseInterceptors(FileInterceptor('file')) async uploadFile(@UploadedFile('file') file: any) { console.log(file) return await this.fileUploadService.uploadFile(file); }
解决方法
Swagger显示"--"空选项的核心原因是这些枚举字段未被标记为必填项,默认会给可选字段添加空选项。以下两种方式均可解决:
方式1:直接修改@ApiBody的Schema配置
在schema中添加required数组,将需要移除空选项的字段加入其中,明确标记为必填:
@ApiBody({ required: true, schema: { type: 'object', // 标记字段为必填 required: ['FileModule', 'FileType', 'FileCategory', 'file'], properties: { FileModule:{type:'string', enum:[FileModule.GEOXING, FileModule.common], description: "选择要上传的模块"}, FileType:{type:'string', enum:[FileType.IMG, FileType.DOC, FileType.XML], description: "选择文件类型" }, FileCategory:{type:'string', enum:[FileCategory.SITE, FileCategory.EXHIBITOR, FileCategory.SERVICE], description: "选择文件分类"}, file: { type: 'string', format: 'binary', }, }, }, })
方式2:使用DTO类(更符合NestJS规范)
创建专门的DTO类,通过@ApiProperty装饰器明确配置字段必填,同时结合class-validator做参数校验:
- 定义UploadDTO:
import { ApiProperty } from '@nestjs/swagger'; import { IsEnum, IsNotEmpty } from 'class-validator'; export class UploadDTO { @ApiProperty({ enum: FileModule, description: "选择要上传的模块", required: true, }) @IsEnum(FileModule) @IsNotEmpty() FileModule: FileModule; @ApiProperty({ enum: FileType, description: "选择文件类型", required: true, }) @IsEnum(FileType) @IsNotEmpty() FileType: FileType; @ApiProperty({ enum: FileCategory, description: "选择文件分类", required: true, }) @IsEnum(FileCategory) @IsNotEmpty() FileCategory: FileCategory; @ApiProperty({ type: 'string', format: 'binary', description: "上传的文件", required: true, }) file: any; }
- 修改控制器接口:
@Post('upload') @ApiConsumes('multipart/form-data') async uploadFile( @Body() dto: UploadDTO, @UploadedFile('file') file: any ) { console.log(file) return await this.fileUploadService.uploadFile(file); }
两种方式都能让Swagger识别字段为必填,从而自动移除下拉列表中的"--"空选项。
内容的提问来源于stack exchange,提问作者umer
相关产品推荐
相关产品推荐

