当前位置:网站首页>Best practices of swagger in egg project
Best practices of swagger in egg project
2022-06-24 13:23:00 【CS Xiaoyao Sword Fairy】
swagger stay egg Best practices in the project
Write By CS Xiaoyao sword immortal
My home page : csxiaoyao.com
GitHub: github.com/csxiaoyaojianxian
Email: [email protected]
QQ: 1724338257
1. background
swagger It's a RESTful The interface is based on YAML、JSON Language documentation and code generation tools online , It allows Deployment Management API Become simpler than ever .swagger stay java Widely used , Other languages can also be easily integrated . This paper is based on node.js Enterprise application framework egg.js For example , Integrate swagger To automatically generate interface documents based on function annotations .
2. Best practices
2.1 Project structures,
Reference link :https://github.com/csxiaoyaojianxian/JavaScriptStudy/tree/master/17-nodejs/20-egg-swagger-doc
egg There are two ways to build : Quick build and normal build . Because this case is relatively simple , To avoid unnecessary configuration of the project , The common construction method is used here , You can refer to the link above , The project directory structure is as follows :
egg-example
├── app
│ ├── contract
│ │ └── format.js
│ ├── controller
│ │ └── home.js
│ └── router.js
├── config
│ └── config.default.js
│ └── plugin.js
└── package.json among , Contains a route /index Called HomeController Controller index Method , This route will be swagger Handle .
2.2 egg-swagger-doc install
Reference resources npm project : https://www.npmjs.com/package/egg-swagger-doc stay egg Install... In the project swagger:
$ npm i egg-swagger-doc --save
2.3 swagger The plug-in configuration
First, in the egg Enable swaggerdoc plug-in unit :
// {app_root}/config/plugin.js
exports.swaggerdoc = {
enable: true, // Is it enabled?
package: 'egg-swagger-doc' // Specify the package name
}And then config Add... To the configuration file swaggerdoc Plug in configuration information :
// {app_root}/config/config.default.js
exports.swaggerdoc = {
dirScanner: './app/controller', // Configure the controller path for auto scan
apiInfo: {
title: ' Interface document ', // The title of the interface document
description: 'swagger Test interface documentation ', // Interface document description
version: '1.0.0', // Interface document version
termsOfService: 'http://swagger.io/terms/', // Conditions of service
contact: {
email: '[email protected]' // Contact information
},
license: {
name: 'Apache 2.0',
url: 'http://www.apache.org/licenses/LICENSE-2.0.html'
},
},
basePath: '/', // Configure the base path
schemes: ['http', 'https'], // Configure supported protocols
consumes: ['application/json'], // Specifies the submitted content type to process the request (Content-Type), Such as application/json、text/html
produces: ['application/json'], // Specify the type of content returned , Only when the request In the request header (Accept) The specified type is included in the type to return
securityDefinitions: {}, // Configure interface security authorization mode
enableSecurity: false, // Whether to enable Authorization , Default false
// enableValidate: true, // Whether to enable parameter verification , Default true
routerMap: false, // Whether to enable automatic route generation ( Experimental function ), Default true
enable: true // Default true
}2.4 Annotation parameter writing
The writing of parameters is divided into two parts :controller and contract, After the plug-in is imported , If you do not modify the default configuration , After the application starts , Will automatically scan app/controller and app/contract The files under the .controller by api The controller , and contract The file under is the defined request body and response body .
The comments for the controller are divided into two parts , The first comment block for each controller must contain @controller Can be resolved to a controller , Then it will analyze the... Contained under the controller one by one api notes .
/**
* @controller HomeController
*/
class HomeController extends Controller {
/**
* @router get /index route
* @summary Subtitle information of the interface
* @description Description of the interface
* @request query integer id For parameters id Description of
* @request query string name For parameters name Description of
* @response 200 indexJsonBody
*/
async index () {
...
}
}and contract The following defines the common request body and response body , You can constrain the format .
const JsonBody = {
code: { type: 'number', required: true, example: 0 },
message: { type: 'string', required: true, example: 'success' },
data: { type: 'Enum', required: true, example: [] },
}
module.exports = {
indexJsonBody: {
...JsonBody,
data: { type: 'string', example: 'test' },
},
};2.5 Generate
After the configuration , perform dev Script , You can open /swagger-ui.html See the generated document .
$ npm run dev
3. Parameter description
swagger There are the following commonly used comments :
@Controller {ControllerName}
@Router {Mothod} {Path}
@Request {Position} {Type} {Name} {Description}
@Response {HttpStatus} {Type} {Description}
@Deprecated
@Description {Description}
@Summary {Summary}about swagger Annotation parameter details , You can refer to https://www.npmjs.com/package/egg-swagger-doc, You can also do it in swagger Generated by cross reference in the editor https://editor.swagger.io.
4. Reference documents
- my github:https://github.com/csxiaoyaojianxian/JavaScriptStudy/tree/master/17-nodejs/20-egg-swagger-doc
- npm:https://www.npmjs.com/package/egg-swagger-doc
- editor:https://editor.swagger.io
边栏推荐
- Sqlserver 2000 has long-lasting vitality
- 8 lines of code to teach you how to build an intelligent robot platform
- CVPR 2022 | 美团技术团队精选论文解读
- Attack popular science: DDoS
- 敏捷之道 | 敏捷开发真的过时了么?
- 39 - read XML node and attribute values
- 【数据挖掘】期末复习(样卷题目+少量知识点)
- The difference between apt and apt get
- ERR AUTH< password> called without anypassword configured for the default user. Ar
- DTU上报的数据值无法通过腾讯云规则引擎填入腾讯云数据库中
猜你喜欢

YOLOv6:又快又准的目标检测框架开源啦

手把手教你用AirtestIDE无线连接手机!

简述聚类分析

Nifi from introduction to practice (nanny level tutorial) - environment

Kubernetes集群部署

hands-on-data-analysis 第三单元 模型搭建和评估

C语言中常量的定义和使用

CVPR 2022 - Interpretation of selected papers of meituan technical team

CVPR 2022 | 美团技术团队精选论文解读

Quickly understand the commonly used message summarization algorithms, and no longer have to worry about the thorough inquiry of the interviewer
随机推荐
go Cobra命令行工具入门
“我这个白痴,招到了一堆只会“谷歌”的程序员!”
Leetcode 1218. 最长定差子序列
39 - read XML node and attribute values
“有趣” 是新时代的竞争力
What if the WordPress website forgets its password
The difference between apt and apt get
[data mining] final review (sample questions + a few knowledge points)
Common special characters in JS and TS
我開導一個朋友的一些話以及我個人對《六祖壇經》的一點感悟
How to create a new empty branch in the web development process of easyrtc?
Optimization of MP4 file missing seconds caused by TS files when downloading videos from easydss video platform
"I, an idiot, have recruited a bunch of programmers who can only" Google "
Vipshop's "special sale" business is no longer easy to do?
16 safety suggestions from metamask project to solid programmers
线程同步的基石AbstractQueuedSynchronizer详解
Comparator sort functional interface
【概率论期末抱佛脚】概念+公式(不含参数估计)
[database] final review (planning Edition)
初中级开发如何有效减少自身的工作量?