NestJS Swagger:如何通过普通注释传递@ApiTags等装饰器配置?
NestJS Swagger 启用introspectComments后用注释配置API文档
首先得确保你已经在Swagger配置中开启了introspectComments选项,配置代码如下:
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); const config = new DocumentBuilder() .setTitle('Your API') .setDescription('API description') .setVersion('1.0') .build(); const document = SwaggerModule.createDocument(app, config, { introspectComments: true, // 开启注释解析功能 }); SwaggerModule.setup('api', app, document); await app.listen(3000); } bootstrap();
接下来是你提到的几个装饰器对应的注释写法:
1. 替代@ApiTags
在控制器类上方用@tags注释指定标签,多个标签可以用逗号分隔:
/** * @tags MyController */ @Controller() export class MyController { // ... }
2. 替代@ApiOperation(含operationId)
在接口方法上方用以下JSDoc标签配置:
@operationId:对应装饰器里的operationId字段@summary:对应summary字段@description:对应description字段
写法示例:
/** * @operationId message * @summary Send Message * @description Using this endpoint you can pass in hello */
3. 替代@ApiResponse
用@response标签,格式为@response <状态码> <描述> <返回类型>,如果不需要指定类型可以省略最后一项:
/** * @response 200 Return Hello Message Response. MessageResponseEntity */
完整示例代码
把所有注释整合后,你的控制器代码会变成这样:
import { Controller, Post, Body } from '@nestjs/common'; import { HelloEntity } from './hello.entity'; import { MessageResponseEntity } from './message-response.entity'; import { HelloService } from './hello.service'; /** * @tags MyController */ @Controller() export class MyController { constructor(private readonly helloService: HelloService) {} /** * @operationId message * @summary Send Message * @description Using this endpoint you can pass in hello * @response 200 Return Hello Message Response. MessageResponseEntity * @body message string */ @Post() async create(@Body() message: string): Promise<HelloEntity> { return await this.helloService.message(message); } }
注意事项
- 确保所有用到的实体类(比如
MessageResponseEntity)已经在当前文件中导入,Swagger才能正确识别类型 - 注释格式要严格遵循JSDoc规范,标签名称和参数不能写错
- 其他装饰器(比如示例中的
@ApiBody)也可以用对应的JSDoc标签(如@body)替代
内容的提问来源于stack exchange,提问作者Dinesh
相关产品推荐
相关产品推荐

