前后端分离时,前端对接口都需要有接口文档,根据接口文档写接口方法,看文档还要去写接口方法基本都是粘贴复制,把这个机械的任务解除了
我们可以根据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);
};
生成代码就和上图不一样了具体可以试试