当前位置:网站首页>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
边栏推荐
- 39 - read XML node and attribute values
- Integrated API interface code of domestic express companies for intra city distribution and ordering - Express 100
- 我从根上解决了微信占用手机内存问题
- Resolve symbol conflicts for dynamic libraries
- Interviewer: the MySQL database is slow to query. What are the possible reasons besides the index problem?
- Main steps of system test
- 谁是鱼谁是饵?红队视角下蜜罐识别方式汇总
- 实现领域驱动设计 - 使用ABP框架 - 创建实体
- How stupid of me to hire a bunch of programmers who can only "Google"!
- Boss direct employment IPO: both the end and the beginning
猜你喜欢

DTU上报的数据值无法通过腾讯云规则引擎填入腾讯云数据库中

openGauss内核:简单查询的执行

The data value reported by DTU cannot be filled into Tencent cloud database through Tencent cloud rule engine

Use terminal to activate CONDA service in pypharm (the ultimate method is definitely OK)

Opengauss kernel: simple query execution

I have fundamentally solved the problem of wechat occupying mobile memory

Without home assistant, zhiting can also open source access homekit and green rice devices?

Understanding openstack network

Several common DoS attacks

面试官:MySQL 数据库查询慢,除了索引问题还可能是什么原因?
随机推荐
华为AppLinking中统一链接的创建和使用
Internet of things? Come and see Arduino on the cloud
Sqlserver 2000 has long-lasting vitality
Creation and use of unified links in Huawei applinking
手机开户后多久才能通过?在线开户安全么?
爱可可AI前沿推介(6.24)
Detailed explanation of abstractqueuedsynchronizer, the cornerstone of thread synchronization
Brief introduction to cluster analysis
Attack Science: ARP attack
[database] final review (planning Edition)
How to create a new empty branch in the web development process of easyrtc?
The text to voice function is available online. You can experience the services of professional broadcasters. We sincerely invite you to try it out
Ask a question about SQL view
"I, an idiot, have recruited a bunch of programmers who can only" Google "
脚本之美│VBS 入门交互实战
How can the new webmaster avoid the ups and downs caused by SEO optimization?
“我这个白痴,招到了一堆只会“谷歌”的程序员!”
What is SCRM? What is the difference between SCRM and CRM
Are you still working hard to select *? Then put away these skills
Implement Domain Driven Design - use ABP framework - update operational entities