依赖安装
由于我的node是koa项目所以需要安装如下依赖包, 如果是express项目将koa2-swagger-ui
换成swaggeer-ui-express
npm i koa2-swagger-ui swagger-jsdoc -S
koa2-swagger-ui
将swagger JSON转为页面,返回至客户端浏览
swagger-jsdoc
在代码中通过注释的形式,生成swagger JSON
【swagger参考文档】:https://xiaoxiami.gitbook.io/swagger/swagger-php-wen-dang/swaggerde-jiang-jieff08-explained
【swagger参考文档】:https://help.coding.net/docs/document/api/import/openapi.html
【swagger-editor】: https://editor.swagger.io/ 所见即所得
重要配置代码
swagger-jsdoc能识别的块状代码
/**
* @swagger <- 识别标识
* /login: <- 接口地址
* post: <- 请求方式
* description: 应用登录接口 <- 文字描述
* tags: [用户登录] <- 标签,可以将接口分类
* produces: <- 返回类型定义
* - application/json <- 具体的类型
* parameters: <- 参数
* - $ref: '#/parameters/username' <- 第一种参数表达方式,从提取的parameters引入
* - name: password <- 第二种参数表达方式,在当前目录写入
* description: 用户密码 <- 参数描述
* in: formData <- 参数传递时放置的位置
* required: true <- 是否必填
* type: string <- 参数类型
* responses: <- 响应体
* '200': <- 状态码
* description: OK <- 描述
* schema: <- 返回数据结构
* type: object, <- 类型
"Login": {
"required": ["username", "password"],
"properties": {
"username": {
"type": "string"
},
"password": {
"type": "string"
},
"path": {
"type": "string"
}
}
}
*/
注释写法
/**
* @swagger
* /api/scdiy/build: # 接口地址
* post:
* description: 用户生产代码打包
* tags: [用户生产代码打包]
* produces:
* - application/zip
* parameters:
* - name: gitName
* description: 仓库名称
* in: body
* required: true
* type: string
* schema:
* type: object
* required: [gitName]
* properties:
* gitName:
* type: string
* default: 'baseline-web'
* responses:
* '200':
* description: OK
* schema:
* type: object
* $ref: '#/deFinitions/build'
*/
/**
* @swagger
* deFinitions:
* build:
* required:
* - gitName
* properties:
* gitName:
* type: string
*/
以上为swagger-jsdoc支持的写法,注意不要使用tab进行缩进处理,yaml不支持tab缩进,会产生YAMLSemanticError错误
swagger配置过程
- 通过路由配置/swagger.json, 返回swagger的json配置内容
const router = require('koa-router')() //引入路由函数
const swaggerJSDoc = require('swagger-jsdoc')
const path = require('path')
const swaggerDeFinition = {
swagger: "2.0",
info: {
title: 'xxxx',
version: '1.0.0',
description: 'API',
},
basePath: '/' // Base path (optional)
};
const routerConf = path.resolve(__dirname, '../routes/*.js');
const parametersConf = 'swagger/parameters.yaml';
const options = {
swaggerDeFinition,
apis: [routerConf, parametersConf],
};
const swaggerSpec = swaggerJSDoc(options)
console.log(swaggerSpec, 'swaggerSpec')
// Todo:通过路由获取生成的注解文件, 通过json配置,接口不接受预检请求
// const swaggerSpec = require('./swagger.spec.json')
router.get('/swagger.json', async function (ctx) {
ctx.set('Content-Type', 'application/json');
ctx.body = swaggerSpec;
})
module.exports = router
- 在服务启动入口将json通过koa2-swagger-ui进行可视化
const swagger = require('./swagger/swagger.js');
const { koaSwagger } = require('koa2-swagger-ui')
app.use(swagger.routes(), swagger.allowedMethods());
app.use(koaSwagger({
routePrefix: '/swagger', // 接口文档访问地址
swaggerOptions: {
url: '/swagger.json', // example path to json 其实就是之后swagger-jsdoc生成的文档地址
}
}));