1、NestJS创建接口
- NestJS一般使用命令去创建相关文件,
- 使用命令
nest g res users 这样就创建了一个users文件夹,里面包含了controller、service、dto、entities等
2、实现Swagger接口文档
-
Swagger 是什么
Swagger是一个用于生成、描述和调用RESTful接口的Web服务。通俗的来讲,Swagger就是将项目中所有(想要暴露的)接口展现在页面上,并且可以进行接口调用和测试的服务。
Swagger遵循了OpenAPI规范,OpenAPI是Linux基金会的一个项目,试图通过定义一种用来描述API格式或API定义的语言,来规范RESTfuI服务开发过程。swagger.io/
- RestAPI接口的展现
- RestAPI测试
- RestAPI Mock数据生成
-
创建Swagger文档
-
安装nest的swagger插件,使用命令
npm i @nestjs/swagger -
然后在src下创建doc.ts去创建生成文档的方法
import { SwaggerModule, DocumentBuilder } from "@nestjs/swagger"; import * as packageConfig from '../package.json'
export const generateDocument = (app) => { const options = new DocumentBuilder() .setTitle(packageConfig.name) .setDescription(packageConfig.description) .setVersion(packageConfig.version) .addBearerAuth() // 允许token鉴权 .build(); const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('/api/v1',app,document)}
-
这里使用了本地的package里的一些内容作为文档标题和描述,也可以自定义内容,若想引入package的json内容,需要在tsconfig里修改一下配置项,添加或修改此配置项,修改为true
- 然后就可以引入了,否则会报错,提示你要修改如上配置项
-
然后在main中导入并使用
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { generateDocument } from './doc';
async function bootstrap() { const app = await NestFactory.create(AppModule); // Swagger文档创建 generateDocument(app) await app.listen(3000); } bootstrap();
-
Swagger常用注解
-
分组标签
我们可以为每一套接口写一个注解,用 @ApiTags(),给一组接口注释,方便我们去找接口
- 为每个接口添加 注解
@ApiOperation({ summary: '新增用户'}),方便找到对应接口
- 可以使用注解
@ApiBearerAuth()来说明,哪些接口需要鉴权