我们都知道在前后端分离开发中,后端是需要给前端提供接口文档的。接口文档中需要包含请求类型,传参格式,响应格式等等。而在 NestJS 中接口文档是可以集成到项目之中的,本篇文章将介绍 NestJS 如何生成 RESTFUL 接口的文档 swagger
安装使用
安装@nestjs/swagger
,swagger-ui-express
(底层为 express)
pnpm install --save @nestjs/swagger swagger-ui-express
然后在main.ts
进行引入配置
...
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
const app = (await NestFactory.create) < NestExpressApplication > AppModule;
...
const options = new DocumentBuilder()
.setTitle('后台管理系统') // 标题
.setDescription('后台管理系统接口文档') // 描述
.setVersion('1.0') // 版本
.build();
const document = SwaggerModule.createDocument(app, options);
//配置swgger地址
SwaggerModule.setup('/api/swagger', app, document);
await app.listen(3000);
}
bootstrap();
启动项目访问http://localhost:3000/api/swagger
就可以看到 swagger 界面了

接口配置
我们看到上面所有接口都是在一起没有分类的,并且也没有请求和返回参数格式等,所以我们需要对其再进行一些配置,这里就以auth/login
接口为例
来到auth.controller.ts
中,引入ApiOperation
,ApiTags
import { Controller, Post, Body } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LoginAuthDto } from './dto/login-auth.dto';
import { Public, Permissions } from 'src/public/public.decorator';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
@ApiTags('登录验证模块')
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@ApiOperation({
summary: '登录接口', // 接口描述信息
})
@Public()
@Post('login')
login(@Body() loginAuthDto: LoginAuthDto) {
return this.authService.login(loginAuthDto);
}
@Public()
@Post('test')
test() {
return 1;
}
}
刷新文档页面就可以看到我们加的分组和接口描述信息了

接下来我们再配置一下入参信息,入参信息需要在login-auth.dto.ts
引入ApiProperty
(定义 post 请求参数)进行配置
import { IsNotEmpty, Length } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
export class LoginAuthDto {
@IsNotEmpty({
message: '用户名不能为空',
})
@Length(2, 10, {
message: '用户名长度必须为2-10之间',
})
@ApiProperty({
example: 'admin',
description: '用户名',
})
username: string;
@IsNotEmpty()
@Length(5, 15, {
message: '密码长度必须为5-15之间',
})
@ApiProperty({
example: 'admin',
description: '密码',
})
password: string;
}
然后再看文档页面

同时可以点击 try it out 按钮进行接口的调用

有了请求参数格式,还需要提供返回数据格式给前端,返回参数的定义可以用ApiOkResponse
进行配置,如
@ApiOkResponse({ description: '登录成功返回', type: LoginResponse })
其中LoginResponse
需要我们根据具体格式自定义,这里新建一个文件定义auth
模块的接口返回格式(vo/auth.vo.ts)
import { ApiProperty } from '@nestjs/swagger';
export class LoginResponse {
@ApiProperty({ example: 200 })
code: number;
@ApiProperty({ example: 'eyJhbGciOiJ...' })
data: string;
@ApiProperty({ example: '请求成功' })
describe: string;
}
然后在auth.controller.ts
进行响应数据的配置
...
import { ApiOperation, ApiTags, ApiOkResponse } from '@nestjs/swagger';
import { LoginResponse } from './vo/auth.vo';
@ApiTags('登录验证模块')
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@ApiOperation({
summary: '登录接口', // 接口描述信息
})
@ApiOkResponse({ description: '登录成功返回', type: LoginResponse })
@Public()
@Post('login')
login(@Body() loginAuthDto: LoginAuthDto) {
return this.authService.login(loginAuthDto);
}
}
刷新 swagge,就会看到我们定义的响应数据了

添加 jwt token
因为有些接口需要登录才能访问,所以需要在 swagger 中配置 token,其实很简单,只需要在 main.ts 再加个 addBearerAuth()函数即可
const options = new DocumentBuilder()
.setTitle('后台管理系统') // 标题
.setDescription('后台管理系统接口文档') // 描述
.setVersion('1.0') // 版本
.addBearerAuth()
.build();
然后在需要认证的接口加上@ApiBearerAuth()
装饰器即可,比如auth/test
接口
@ApiBearerAuth()
@Post('test')
test() {
return 1;
}
点击Authorization
,将调用登录接口取得的 token 输入进去即可调用加了权限的接口了

调用auth/test

我们发现验证通过了。
写在最后
本篇文章介绍了 NestJS 中 Swagger 的使用,使用 Swagger 极大的方便了前后端的接口对接,同时减少了后端人员编写接口文档的时间。提高了开发效率增加了摸鱼时间。
代码仓库地址留言获取哦~
原文始发于微信公众号(web前端进阶):Vue3 + Nest 实现权限管理系统 后端篇(五): 生成Swagger在线文档
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/232249.html