nestjs中swagger的基本使用
安装
$ npm install --save @nestjs/swagger swagger-ui-express
//如果使用fastify,则必须安装fastify-swagger而不是swagger-ui-express:
$ npm install --save @nestjs/swagger fastify-swagger
朴素使用
main.ts
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle('this is a title')
.setDescription('this is a description')
.setVersion('1.0')
.addTag('cat')
.addTag('dog')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
await app.listen(3000);
}
重点:用ApiTags装饰每一个Controller,才能把它们按名字分类展示
import { ApiTags } from '@nestjs/swagger';
app.controller.ts
@ApiTags()
@Controller()
export class AppController { ... }
cat.controller.ts
@ApiTags('cat')
@Controller('cat')
export class CatController { ... }
dog.controller.ts
@ApiTags('dog')
@Controller('dog')
export class DogController { ... }
如上便得到如下效果:
通过装饰器对接口更详细地说明
import { Controller, Get, Param } from '@nestjs/common';
import { ApiTags, ApiParam } from '@nestjs/swagger';
@ApiTags('dog')
@Controller('dog')
export class DogController {
@Get('/onedog/:name')
// 通过ApiParam装饰器,来描述接口需要哪些参数
@ApiParam({ name: 'name', type: String, description: '姓名' })
@ApiParam({ name: 'gender', type: String, description: '性别' })
aGetRequest(
@Param('name') name: string,
@Param('gender') gender: string
): string {
return `a ${gender} named ${name} has lunched a get request`
}
}
如上便得到如下效果:
除了ApiParam装饰器外还有很多别的装饰器可用,可自行百度,用法大同小异