swagger
用于提供给前端接口文档
注册swagger
安装命令如下
npm install @nestjs/swagger swagger-ui-express
在main.ts注册swagger
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
xxxxxx
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
const options = new DocumentBuilder().setTitle('接口文档标题').setDescription('描述,。。。').setVersion('1').build()
const document = SwaggerModule.createDocument(app,options)
SwaggerModule.setup('/api-docs',app,document)
await app.listen(3000);
}
bootstrap();
访问http://localhost:3000/api-docs
,
分组
在每个controller中使用ApiTags分组,如user使用
效果如下
描述
使用ApiOperation
为单个的接口添加描述
import { ApiOperation } from '@nestjs/swagger';
xxxxxx
@ApiOperation({ summary: '概要', description: '详细描述' })
动态参数
使用ApiParam
为单个接口添加参数描述
import { ApiParam } from '@nestjs/swagger';
xxxxxx
@ApiParam({
name: 'id',
type: 'string',
required: true,
description: '传个id',
})
Query
使用ApiQuery
为单个接口添加query参数描述
import { ApiQuery } from '@nestjs/swagger';
xxxxxx
@ApiQuery({
name: 'myrole',
type: 'string',
required: true,
description: '传个权限字符',
})
post
与以上类似除了使用ApiBody外post还可以结合dto,使用ApiProperty来添加
效果如下
返回信息
使用ApiResponse
为单个接口添加返回结果描述
import { ApiResponse } from '@nestjs/swagger';
xxxxxx
@ApiResponse({
status: 403,
description: '返回内容描述',
})
token
main.ts
const options = new DocumentBuilder()
.addBearerAuth()
.setTitle('接口文档标题')
.setDescription('描述,。。。')
.setVersion('1')
.build();
给controller添加ApiBearerAuth
在访问user的路由时需要填写授权码
访问时自动带上