開發環境:nodejs + express
需求:需要使用swagger將介面匯入到YApi中,but but but 沒用過!
首先附上參考管網:https://swagger.io/docs/specification/authentication/
鑒于網上教程大多尚不完整,特此撰寫(僅供參考)
完成后樣例:

1.在app.js檔案中引入swagger
具體代碼如下
require("./swagger")(app);
2.在專案下根目錄下新建swagger檔案夾并新建index.js檔案用于撰寫swagger的基本設定,

具體代碼如下:
var path = require("path");
var express = require("express");
var swaggerUi = require("swagger-ui-express");
var swaggerJSDoc = require("swagger-jsdoc");
//author:LianSP
//comment:swagger請求路徑:http://localhost:9009/swagger
// 配置 swagger-jsdoc
const options = {
definition: {
// 采用的 openapi 版本,***注意該版本直接影響了管網參考版本,
openapi: "3.0.0",
// 頁面基本資訊
info: {
title: "數字權益區塊鏈", //設定swagger的標題,(專案名稱)
version: "1.0.0", //設定版本
},
//設定鎖,用于
components: {
securitySchemes: {
oauth2: {
type: "oauth2",
flows: {
authorizationCode: {
authorizationUrl: "/oauth/dialog",
tokenUrl: "/oauth/token",
},
},
},
},
},
},
// 去指定專案路徑下收集 swagger 注釋,用于生成swagger檔案,
apis: [path.join(__dirname, "../routes/**/*.js")],
};
var swaggerJson = function (req, res) {
res.setHeader("Content-Type", "application/json");
res.send(swaggerSpec);
};
const swaggerSpec = swaggerJSDoc(options);
var swaggerInstall = function (app) {
if (!app) {
app = express();
}
// 此路徑用于向YApi匯入介面檔案
app.get("/swagger.json", swaggerJson);
// 使用 swaggerSpec 生成 swagger 檔案頁面,并開放在指定路由,swagger訪問前綴
app.use("/swagger", swaggerUi.serve, swaggerUi.setup(swaggerSpec));
};
module.exports = swaggerInstall;
3.至此完成了swagger的設定,接下來需要撰寫介面引數,以routes檔案夾下的 js檔案中某個介面為例(本次以post請求為例)
然后需要在此介面的上方,撰寫注釋,如下圖
具體代碼如下:
/**,
* @swagger
* /api/baseCoinBalance:
* post:
* tags:
* - 平臺幣 #介面分類
* summary: 測驗1 #介面備注
* description: 測驗 #介面描述
* consumes:
* - "application/json" #介面接收引數方式
* requestBody: #撰寫引數接收體
* required: true #是否必傳
* content:
* application/json:
* schema: #引數備注
* type: object #引數型別
* properties:
* fromAddress:
* type: string #引數型別
* description: 發送者錢包地址 #引數描述
* example: #請求引數樣例,
* fromAddress: "string"
* responses: #撰寫回傳體
* 1000: #回傳code碼
* description: 獲取底層幣余額成功 #回傳code碼描述
* content:
* application/json:
* schema:
* type: object
* properties:
* res_code: #回傳的code碼
* type: string
* description: 回傳code碼
* res_msg: #回傳體資訊,***注意寫的位置一定要和res_code對齊,
* type: string #回傳體資訊型別
* description: 回傳資訊
* 1001:
* description: 獲取底層幣余額失敗
* */
如需使用其他方法,請參考管網

4.啟動專案,在瀏覽器輸入swagger路徑 http://127.0.0.1:9009/swagger,如下圖樣例所示,即為配置成功,
5.將介面檔案匯入YApi中,打開YApi,

6.至此完成了swagger匯入到YApi中的所有操作,(會持續更新,不斷完善nodejs使用swagger)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/253961.html
標籤:區塊鏈
