前後端分離時,前端對接口都需要有接口文檔,根據接口文檔寫接口方法,看文檔還要去寫接口方法基本都是粘貼複製,把這個機械的任務解除了
我們可以根據swagger接口文檔,前端來自動生成接口方法
根據swagger.json文件來npm 生成接口方法
接口信息都截去了
大概數據結構如下我們主要需要用到的是path裏的
path: {
"/api/****/Login": {
"post": {
"tags": [
"Account"
],
"summary": "登錄授權",
"operationId": "Login",
"consumes": [
"application/json-patch+json",
"application/json",
"text/json",
"application/*+json"
],
"produces": [
],
"parameters": [{
"name": "input",
"in": "body",
"description": "",
"required": false,
"schema": {
"$ref": "#/definitions/**"
}
}],
"responses": {
"200": {
"description": "Success"
}
}
}
},
}
一、那我們需要做的就是解析這段json然後生成js文件, 首先安裝依賴
npm install --save-dev swagger-parser
二、項目根目錄下新建文件apigen.js
同時配置npm 命令
"api": "node apigen.js",
三、根據自身項目常用規則編寫apigen.js裏的方法
個人習慣常用規則如下
四、apigen.js 編寫如下
const fs = require('fs')
const path = require('path')
const parse = require('swagger-parser')
const swaggerUrl = 'https://*****/swagger/v1/swagger.json'
// api接口方法存放目錄
const API_PATH = path.resolve(__dirname, './src/apitest')
// 判斷目錄是否存在
const isExist = (lastPath = '') => {
const privatePath = `${lastPath ? API_PATH + '/' + lastPath : API_PATH}`
const stat = fs.existsSync(privatePath)
if (!stat) {
fs.mkdirSync(privatePath)
}
if (!lastPath) {
const configPath = `${API_PATH}/config.jsx`
// api 目錄下寫入 config文件
fs.access(configPath, function (err) {
if (err && err.code === 'ENOENT') {
fs.writeFileSync(`${API_PATH}/config.jsx`, 'export const ip = \'https://test.××××.com/\'')
}
})
}
}
// 整理出相同模塊路徑
const getModules = (map) => {
map.forEach((value, key) => {
writeFileApi(key, value)
})
}
// 寫入jsx
const writeFileApi = (fileName, apiData) => {
// api.jsx
let tplApi = 'import { ip } from \'../config\' \n\nexport default {\n'
// index.jsx
let tplIndex = 'import { post, get, put, delete } from \'../../utils/request\'\nimport api from \'./api\'\n\n'
const apiDataLen = apiData.length
for (let i = 0; i < apiDataLen; i++) {
const item = apiData[i]
const itemKeys = Object.keys(item) // 請求方法
const itemTagKey = itemKeys[0] // 方法數據信息
const itemKeysFirest = item[itemTagKey]
const pathName = itemKeysFirest.operationId
const allPath = item.allPath
tplApi = `${tplApi} ${pathName}: \`\${ip}${allPath}\`,\n`
tplIndex = `${tplIndex}\n//${itemKeysFirest.summary}\n` +
`export const ${pathName} = (params) => {\n` +
` return ${itemTagKey}(api.${pathName}, params)\n}`
}
tplApi = tplApi + '\n}'
fs.writeFileSync(`${API_PATH}/${fileName}/api.jsx`, tplApi)
fs.writeFileSync(`${API_PATH}/${fileName}/index.jsx`, tplIndex)
}
// 入口方法
const apigen = async () => {
isExist()
try {
const parsed = await parse.parse(swaggerUrl)
const paths = parsed.paths
const pathsKeys = Object.keys(paths) // 獲取url路徑
const pathsKeysLen = pathsKeys.length
const modulesMap = new Map()
for (let i = 0; i < pathsKeysLen; i++) {
const item = pathsKeys[i]
const itemAry = item.split('/')
const pathsItem = paths[item]
let fileName = itemAry[3]
if (!fileName) continue
fileName = fileName.toLowerCase()
// 創建模塊目錄
isExist(fileName)
// 完整路徑
pathsItem.allPath = item
if (modulesMap.has(fileName)) {
const fileNameAry = modulesMap.get(fileName)
fileNameAry.push(pathsItem)
modulesMap.set(fileName, fileNameAry)
} else {
modulesMap.set(fileName, [pathsItem])
}
}
getModules(modulesMap)
} catch (e) {
console.log(e)
}
}
apigen()
五、運行npm 命令就可生成代碼,內容如第三步
六、當然還有更簡單的方法,利用swagger-js-codegen解析json數據內容
npm i --dev-save swagger-js-codegen
大致如下
const gen = async (module) => {
const swagger = await parse.parse(swaggerUrl);
let sourceCode = CodeGen.getReactCode({
className,
swagger
});
const reg = new RegExp(`exports.${module} = ${module};`);
sourceCode = sourceCode.replace(reg, `export default ${className};`);
fs.writeFileSync(`${API_PATH}/${module}.js`, sourceCode);
};
生成代碼就和上圖不一樣了具體可以試試