生成 Swagger API 文档
前言
现在,前后台开发分离已成为一种标准,后台负责提供api,其他功能交给前台来实现,可是项目开发中的沟通成本也随之提升,这部分红本主要体如今前台须要接口文档,可是后台可能没时间写或者其余缘由,致使功能对接缓慢。Swagger
很好的解决了这个问题,它能够动态生成Api接口文档,今天咱们简单说下在 Nest
项目中 集成 Swagger
。
贴出跟进看的文档以方便大家进一步学习 Nest 中文文档 , Swagger
Swagger 简介
-
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化
RESTful
风格的 Web 服务。Swagger 的目标是对 REST API 定义一个标准且和语言无关的接口,可让人和计算机拥有无须访问源码、文档或网络流量监测就能够发现和理解服务的能力。当经过 Swagger 进行正肯定义,用户能够理解远程服务并使用最少实现逻辑与远程服务进行交互。与为底层编程所实现的接口相似,Swagger 消除了调用服务时可能会有的猜想。 -
简单讲 RESTful 架构:
(1)每一个URI代表一种资源; (2)客户端和服务器之间,传递这种资源的某种表现层; (3)客户端通过四个HTTP动词(GET POST PUT DELETE),对服务器端资源进行操作,实现"表现层状态转化"。
安装依赖
yarn add -save @nestjs/swagger
yarn add -save swagger-ui-express
实现
-
这里简单实现一个注册接口
-
基础配置
/* main.ts */ import { NestFactory } from '@nestjs/core'; import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; async function bootstrap() { ... const app = await NestFactory.create(ApplicationModule); /* 启动swagger */ const options = new DocumentBuilder() .addBearerAuth() // 开启 BearerAuth 授权认证 .setTitle('API 文档') .setDescription('API 文档') .setTermsOfService('https://docs.nestjs.cn/8/introduction') .setVersion('0.0.1') .build(); const document = SwaggerModule.createDocument(app, options); // 设置显示路由 SwaggerModule.setup('/doc/swagger-api', app, document); } bootstrap();
-
DTO 配置
/* user.dto.ts */ import { IsString, IsInt } from 'class-validator'; import { ApiProperty } from '@nestjs/swagger'; // 这里用api可实现默认值渲染 export class CreateUserDto { @ApiProperty({ description: '用户名', example: 'auth1' }) @IsString({ message: '用户名称必须为字符串' }) userName: string; @ApiProperty({ description: '密码', example: '123' }) @IsString() passWord: string; @ApiProperty({ description: '年龄', example: 15 }) @IsInt() age: number; @ApiProperty({ description: '身高', example: 150 }) @IsInt() height: number; }
-
user 服务配置
/* user.service.ts */ import { Injectable } from '@nestjs/common'; import { Model } from 'mongoose'; import { InjectModel } from '@nestjs/mongoose'; import { User, UserDocument } from 'src/schema/user.schema'; import { ApiException } from 'src/common/exceptions/api.exception'; import { CreateUserDto } from './dto/user.dto'; import { SharedService } from 'src/shared/shared.service'; @Injectable() export class UserService { constructor( @InjectModel('User') private userTest: Model<UserDocument>, private readonly sharedService: SharedService, ) {} // 注册 async register(createUserDto: CreateUserDto): Promise<any> { // 1. 判断是否已被注册 const user = await this.findUser(createUserDto.userName); // console.log(user); console.log('查看user'); if (user) { throw new ApiException('此用户已注册', 500); } const uuid = '2_M7BAdd92bWJ4P13SICZ'; const salt = '12345678910abcdefg'; const testPas = createUserDto.passWord; const newUser = { ...createUserDto, uuid, testPas, salt }; const createUser = new this.userTest(newUser); const sqlObj = await createUser.save(); if (!sqlObj) { throw new ApiException('网络原因注册失败', 500); } return { data: sqlObj, message: '注册成功', code: 200, }; // return temp; } }
-
路由使用
/* user.controller.ts */ import { Body, Controller, Post } from '@nestjs/common'; import { ApiTags, ApiBearerAuth } from '@nestjs/swagger'; import { CreateUserDto } from './dto/user.dto'; import { UserService } from './user.service'; @ApiBearerAuth() // 使用 BearerAuth 授权 @ApiTags('user') // 在 suagger ui 中给api分类 @Controller('user') export class UserController { constructor(private readonly userService: UserService) {} // 注册接口 @Post('register') async createUser(@Body() body: CreateUserDto) { return this.userService.register(body); } }
效果
-
上面配置好后直接
yarn run start:dev
启动项目 -
在浏览器 URl 中输入
http://localhost:3000/doc/swagger-api/
-
-
可以看到我们的
/api/user/register
路由已经在这里面,并且排列在user
模块里面 -
接下来我们点开该路由可以看到刚才我们配置的默认参数已经在这里面
-
-
点击左侧
Try it out
做出最后的参数修改并发出请求 -
-
可以看到这里请求成功,已经完成用户注册
总结
- 至此我们已经完成在
Nest.js
中使用 Swagger APi 在Nest.js
中配置的基础操作。应该能满足绝大小伙伴的需求,再也不用为手写 APi 文档发愁。 - 还有能多的使用技巧如
类型映射
枚举 schema
等感兴趣小伙伴可以去看一下。