npm i egg-swagger-doc --save // 自动生成接口描述配置
在/config/config.default.js里面配置
config.swaggerdoc = {
dirScanner: './app/controller', // 配置自动扫描的控制器路径。
// 接口文档的标题,描述或其它。
apiInfo: {
title: 'NAPI', // 接口文档的标题。
description: 'swagger-ui for NAPI document.', // 接口文档描述。
version: '1.0.0', // 接口文档版本。
},
schemes: [ 'http', 'https' ], // 配置支持的协议。
consumes: [ 'application/json' ], // 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html。
produces: [ 'application/json' ], // 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回。
securityDefinitions: { // 配置接口安全授权方式。
// apikey: {
// type: 'apiKey',
// name: 'clientkey',
// in: 'header',
// },
// oauth2: {
// type: 'oauth2',
// tokenUrl: 'http://petstore.swagger.io/oauth/dialog',
// flow: 'password',
// scopes: {
// 'write:access_token': 'write access_token',
// 'read:access_token': 'read access_token',
// },
// },
},
enableSecurity: false, // 是否启用授权,默认 false(不启用)。
// enableValidate: true, // 是否启用参数校验,默认 true(启用)。
routerMap: true, // 是否启用自动生成路由,默认 true (启用)。
enable: true, // 默认 true (启用)。
};
在/config/plugin.js配置
module.exports.swaggerdoc = {
enable: true, // 启用 swagger-ui 默认启用
package: 'egg-swagger-doc', // 指定 第三方插件 包名称
};
'use strict';
const Controller = require('egg').Controller;
/**
* @controller ConfigController 注释必写,swagger-doc是根据这段注释来生成接口的 )。
*/
class ConfigController extends Controller {
async single() {
/**
* @summary configsingle
* @description configsingle
* @router get /configsingle
* @request query integer limit
* @request query integer page
*/
//上面的注释一定要,get请求,参数是int类型的limit和page
const result = await this.ctx.service.config.single()
this.ctx.body = {
data:result
}
}
async edit() {
/**
* @summary configedit
* @description configedit
* @router post /configedit
* @request body config value 传入参数
*/
//上面的注释一定要,post请求,json对象为config,post请求必须创建app/contract/type.js 文件
const params = this.ctx.request.body
await this.ctx.service.config.edit(params)
this.ctx.body = {
msg:'edit successful'
}
}
}
module.exports = ConfigController;
module.exports = {
// 默认接口类型
config: {
id: {
type: 'string', required: true, example: '' },
flag: {
type: 'boolean', required: true, example: '' },
refreshtime: {
type: 'integer', required: true, example: '' },
days: {
type: 'integer', required: true, example: '' },
},
}
egg-swagger-doc文档地址:https://www.npmjs.com/package/egg-swagger-doc