前言
作为一个后端服务,API文档是必不可少的,除了接口描述,参数描述之外,自测也非常的方便。NestJS自带了Swagger文档。集成非常简单。
- 由于工程中之前使用了fastify,所以我们要安装以下依赖:
cnpm install @nestjs/swagger
新版本已经不需要安装 fastify-swagger 依赖,默认被内置在
@nestjs/swagger中了。
在nestJS项目跟目录处创建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)
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('/api/doc', app, document);
}
为了节约配置项,
Swagger的配置信息全部取自package.json,有额外需求的话可以自己维护配置信息的文件。
默认情况下,在 TS 开发的项目中是没办法导入 .json 后缀的模块,所以可以在 tsconfig.json 中新增 resolveJsonModule 配置即可。
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false,
"resolveJsonModule": true
}
}
在Main.ts中使用
import { generateDocument } from './doc';
generateDocument(app)
完成上述内容之后,浏览器打开 http://localhost:3000/api/doc 就能看到 Swagger 已经将我们的前面写好的接口信息收集起来了。