当前位置:网站首页>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
边栏推荐
- 简述聚类分析
- CVPR 2022 | 美团技术团队精选论文解读
- Geological disaster early warning monitoring RTU
- How to efficiently analyze online log
- 实现领域驱动设计 - 使用ABP框架 - 创建实体
- “有趣” 是新时代的竞争力
- Ask a question about SQL view
- Creation and use of unified links in Huawei applinking
- Optimization of MP4 file missing seconds caused by TS files when downloading videos from easydss video platform
- I enlighten a friend and my personal understanding of the six patriarchs' Tan Jing
猜你喜欢

Beauty of script │ VBS introduction interactive practice

一文理解OpenStack网络

Quickly understand the commonly used message summarization algorithms, and no longer have to worry about the thorough inquiry of the interviewer

CVPR 2022 | interprétation de certains documents de l'équipe technique de meituan

"Interesting" is the competitiveness of the new era

1. Snake game design

On the value foam of digital copyright works from the controversial nature of "Meng Hua Lu"

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

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

Party, Google's autoregressive Wensheng graph model
随机推荐
On the difference between process and thread
C语言中常量的定义和使用
Common special characters in JS and TS
一文讲透研发效能!您关心的问题都在
【概率论期末抱佛脚】概念+公式(不含参数估计)
问个sql view的问题
强化学习之父Richard Sutton论文:追寻智能决策者的通用模型
J'a i ouvert quelques mots d'un ami et quelques réflexions personnelles sur le livre des six ancêtres
[day ui] affix component learning
Brief introduction to cluster analysis
LVGL库入门教程 - 颜色和图像
YOLOv6:又快又准的目标检测框架开源啦
CVPR 2022 | 美團技術團隊精選論文解讀
The introduction of MySQL memory parameters is divided into two categories: thread exclusive and global sharing
Detailed explanation of abstractqueuedsynchronizer, the cornerstone of thread synchronization
One article explains R & D efficiency! Your concerns are
Sinomeni vine was selected as the "typical solution for digital technology integration and innovative application in 2021" of the network security center of the Ministry of industry and information te
Redis' contribution in the field of microservices
Implement Domain Driven Design - use ABP framework - update operational entities
系统测试主要步骤