目录:
- 依赖库安装
- swagger配置
- swagger网址访问
- swagger添加标签
- swagger权限实现
1、依赖库安装
在命令行终端执行如下命令
pnpm install @nestjs/swagger swagger-ui-express -S
2、swagger配置
在apps/api/main.ts文件中则更加如下配置代码:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
//swagger配置 start
const options = new DocumentBuilder()
.setTitle('接口文档') // 标题
.setDescription('后台管理系统接口文档') // 描述
.setVersion('1.0') // 版本
.build();
const document = SwaggerModule.createDocument(app, options);
//配置swgger地址
SwaggerModule.setup('/api/doc', app, document);
//swagger配置 end
await app.listen(process.env.PORT ?? 8000);
}
bootstrap();
3、swagger网址访问
打开网页输入地址 http://localhost:8000/api/doc 系统显示接口文档如下:
4、swagger添加标签
接口文档展示我们在controller中写的所有接口,但是我们看到上面所有接口都是在一起没有分类的,并且也没有请求和返回参数格式等,所以我们需要对其再进行一些配置。我们以 test 模块为例,来到test.controller.ts中,先引入ApiOperation和ApiTags给整个模块及单个接口添加一些信息:
代码如下:
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { TestService } from './test.service';
import { CreateTestDto } from './dto/create-test.dto';
import { UpdateTestDto } from './dto/update-test.dto';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
@ApiTags('测试模块')
@Controller('test')
export class TestController {
constructor(private readonly testService: TestService) {}
@ApiOperation({
summary: '添加测试', // 接口描述信息
})
@Post()
create(@Body() createTestDto: CreateTestDto) {
return this.testService.create(createTestDto);
}
@Get()
findAll() {
return this.testService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.testService.findOne(+id);
}
@Patch(':id')
update(@Param('id') id: string, @Body() updateTestDto: UpdateTestDto) {
return this.testService.update(+id, updateTestDto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.testService.remove(+id);
}
}
在浏览器中刷新页面,可以看到页面的变化:
接口参数:
配置一下接口入参信息,一般在我们开发过程中,前端传来的数据信息会放在DTO(Data Transfer Object)中。可以看到上面示例接口用的是CreateTestDto,所以我们来到create-test.dto.ts中定义前端传来的参数,再调用 swagger 中的 ApiProperty 定义文档上展示的传参内容
文档显示如下:
返回值参数:
接下来我们在 test 目录下新建vo/create-test.vo.ts用来描述这个接口的返回值。
同时修改controller中接口的返回值描述;
接口文档变化:
5、swagger权限实现
有些接口需要登录才能访问,因此需要在 swagger 中配置 token,只需要在 main.ts 再加个 addBearerAuth()函数即可:
然后在需要认证的接口加上@ApiBearerAuth()装饰器,比如还是这个/test接口:
刷新接口文档,发现接口右侧多了一个锁,点击锁输入token,可以测试接口: