NestJs使用Swagger

113 阅读1分钟

在 NestJS 中集成 Swagger 可以使你更容易地创建、文档化和测试 API。如果用不惯swagger可以不挂载的,直接使用其他测试接口工具也是可以的,比如apifox,posman等

安装

npm install @nestjs/swagger swagger-ui-express --save

项目配置

由于Swaager是属于整个项目的,所以我们会在项目的main.ts文件中配置项目的Swagger。首先需要做的是在包中引入我们的两个对象,用于构建swaager的document以及module

import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const config = new DocumentBuilder()
    .setTitle('Cats example')
    .setDescription('The cats API description')
    .setVersion('1.0')
    .addTag('cats')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);//访问地址:http://localhost:3000/api#/

  await app.listen(3000);
}
bootstrap();

配置模块

模块,需要在具体的controller中,添加@ApiTags()标签。方法添加@ApiOperation()标签

@ApiTags('Health Check')
@Controller()
export class HealthController {
  constructor(private readonly appService: HealthService) {}
  @ApiOperation({ summary: 'OK' })
  @Get('_health')
  getOk(): string {
    return this.appService.getOk();
  }
}