VUE api半自动化封装记录
vue项目中,我们经常会引入路由模块,api模块,vuex模块,还有一些公用组件模块。 每次都手动输入模块和路径,自然难免心生厌恶,只是个名字不一样,每次都得重新写一堆东西。 于是自动化注册和自动化引入,就显得非常重要了。
自动生成api请求文档
const fs = require('fs')
const path = require('path')
const axios = require('axios')
let apiUrl = 'http://xxxxxxxxxxxxxx'
// 上面为需要解析的接口文档地址
axios.get(apiUrl + '/swagger-resources').then(function (response) {
//获取api列表,便利并请求api
let apiList = response.data;
for (let item of apiList) {
axios.get(apiUrl + item.url).then(function (response1) {
//遍历子api列表,生成文件
let apiData = response1;
// console.log('apiData',apiData.data.paths);
let apiMap = {}
for (let urlKey in apiData.data.paths) {
//创建文件路径
let fileName = urlKey.split("/")[1]
if (fileName === 'error') {
continue;
}
//如果目录不存在创建目录
if (!apiMap[fileName]) {
mkdirs(`${__dirname + apiData.data.basePath}`, () => {
})
apiMap[fileName] = [];
}
let apiObj = {
url: parseUrl(urlKey),
}
// console.log(`${__dirname +apiData.data.basePath+ '/' + fileName}`);
// fs.mkdir(`${__dirname +apiData.data.basePath+ '/' + fileName}`,function(err){
// if(err){
// return false
// }
// })
let reuqestData = apiData.data.paths[urlKey];
// 构成请求请求文件
let queryList = [];
//遍历接口类型数据
for (let apiType in reuqestData) {
let apiInfo = reuqestData[apiType];
apiObj.type = apiType
apiObj.description = apiInfo.summary//备注信息
if (urlKey.indexOf("{") != -1) {
var pattern = /\$\{\w+\}/g;
var match = pattern.exec(apiObj.url);
let paramsName = apiObj.url.substring(match.index + 2, match.index + match[0].length - 1);
apiObj.paramsName = paramsName
//识别根据id查询
if (apiObj.url === `/${fileName}/\${id}`) {
//方法名称
apiObj.funName = 'selectById';
}//识别删除
else if (apiObj.url === `/${fileName}/remove/\${id}`) {
//方法名称
apiObj.funName = 'deleteByIds';
} else {
let arr = apiObj.url.split("/");
//超过3节取倒数第二段
if (arr.length >= 4) {
apiObj.funName = arr[arr.length - 2];
} else {
apiObj.funName = fileName + firstUpperCase(paramsName);
console.log('只有2端生成驼峰', apiObj.funName);
//console.error(apiObj.url,"没有方法名")
}
}
} else {
apiObj.paramsName = 'data'
let arr = apiObj.url.split("/");
apiObj.funName = arr[arr.length - 1];
}
apiMap[fileName].push(JSON.parse(JSON.stringify(apiObj)));
}
// fs.writeFile(
// __dirname + `.${reuqestData.basePath}.js`,
// // 我这边是用两个空格来缩进 pages.json,如果喜欢制表符,第三个参数更换你为 \t 即可
// JSON.stringify(router, null, ' '),
// e => e ? console.error(e) : console.log('pages.json 配置文件更新成功')
// )
}
//生成请求文件
for (let fileName in apiMap) {
let request = apiMap[fileName];
//生成文本内容
let fileText = `import http from "@/apis/http.js";\nimport config from "@/config/index.config.js";\n`
//生成请求
for (let i in request) {
let value = request[i];
fileText += `//${value.description}\n`;
if (value.type === 'get') {
fileText += `export const ${value.funName} = (${value.paramsName}) => http.GET(\`\${config.baseUrl}${value.url}\`, ${value.paramsName})\n`;
} else if (value.type === 'post') {
fileText += `export const ${value.funName} = (${value.paramsName}) => http.POST(\`\${config.baseUrl}${value.url}\`, ${value.paramsName})\n`;
}
}
fs.writeFile(
`${__dirname + apiData.data.basePath + '/' + fileName}.js`,
// 我这边是用两个空格来缩进 pages.json,如果喜欢制表符,第三个参数更换你为 \t 即可
fileText,
() => {
}
)
}
});
}
}).catch(function (error) {
console.log(error);
});
//解析请求
function parseUrl(s) {
var pattern = /\{\w+\}/g;
while (true) {
var match = pattern.exec(s);
if (match) {
s = s.replace(match, '$' + match[0]);
}
else {
break;
}
}
console.log(s);
return s;
}
// 递归创建目录 异步方法
function mkdirs(dirname, callback) {
fs.exists(dirname, function (exists) {
if (exists) {
callback();
} else {
// console.log(path.dirname(dirname));
mkdirs(path.dirname(dirname), function () {
fs.mkdir(dirname, callback);
console.log('在' + path.dirname(dirname) + '目录创建好' + dirname + '目录');
});
}
});
}
//首字符驼峰
function firstUpperCase(str) {
return str.replace(/^\S/, s => s.toUpperCase());
}