npm install egg-swagger-doc --save
/* /config/config.default.js */
/ egg-swagger-doc 配置信息。
exports.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 */
'use strict';
// 配置 egg-swagger-doc 插件信息。
exports.swaggerdoc = {
enable: true, // 是否启用。
package: 'egg-swagger-doc', // 指定包名称。
};
/* /app/contract/format.js */
//自动文档约定
module.exports = {
JsonBody: { // 这个名字对应上面 Controller 注释的@response 的 JsonBody。
result: { type: 'string' }, // 服务器返回的数据。
},
};
编写一个controller控制器
'use strict';
const BaseController = require("../base");
/**
* @controller 测试控制器 注释必写,swagger-doc是根据这段注释来生成接口的 )。
*/
class HomeController extends BaseController {
/** ( 注释必写,swagger-doc是根据这段注释来生成接口详细信息的 )。
* @summary 根据ID查询信息。
* @description 根据ID查询信息。
* @router get /api ( get 表示设置请求为 get 请求,最后的 selectById 对应下面的 selectById 方法 )。
* @request query integer Id 需要去查新的ID。( get 对应 query 请求,请求值设定为 integer 纯数字类型,ID 为请求的字段,注意大小写,和下面的方法要一一对应,不然会报错 )。
* @response 200 JsonBody 返回结果。( 对应 contract 里面的验证属性,下面会提到 。)
*/
async index() {
const { ctx } = this;
let result = await this.app.mysql.query(
'select * from user'
);
this.notFound()
}
async v1(){
const { ctx } = this;
ctx.body = "我是v1自动路由";
}
}
module.exports = HomeController;