UNPKG

momodevtools

Version:

file tools

248 lines (234 loc) 7.64 kB
const http = require("http"); // 封装get 请求发送 function get(url) { return new Promise((resolve, reject) => { http .get(url, (res) => { const { statusCode } = res; const contentType = res.headers["content-type"]; let error; // Any 2xx status code signals a successful response but // here we're only checking for 200. if (statusCode !== 200) { error = new Error( "Request Failed.\n" + `Status Code: ${statusCode} ${url}` ); } else if (!/^application\/json/.test(contentType)) { error = new Error( "Invalid content-type.\n" + `Expected application/json but received ${contentType}` ); } if (error) { console.error(error.message); // Consume response data to free up memory res.resume(); return; } res.setEncoding("utf8"); let rawData = ""; res.on("data", (chunk) => { rawData += chunk; }); res.on("end", () => { try { const parsedData = JSON.parse(rawData); resolve(parsedData); } catch (e) { console.error(e.message); reject(e.message); } }); }) .on("error", (e) => { console.error(`Got error: ${e.message}`); reject(e.message); }); }); } /** * 输出注释 * @param {Array} arrData 要写入的内容 * @returns {string} 返回的文本 */ function writeDescription(arrData, space = "") { let res = space + "/*\n"; arrData.forEach((element) => { res += `${space} * ${element}\n`; }); return res + space + " */\n"; } /** * @description 获取每个接口的信息的date * @param {Array} list 列表获取的item 数组 * @returns {string} 返回的文本 */ function getApiDetailasDate(list, yapiConfig) { const len = list.length; let saveData = "const apiData = {\n"; list.forEach((e, i) => { let portData = { url: e.path.split("/{")[0], method: e.method, }; const itemDesc = writeDescription([ `@description ${e.title} 接口id ${e._id}`, `@description 文档地址 ${yapiConfig.host}/project/${yapiConfig.pid}/interface/api/${e._id}`, ]); portData = `${e._id} : ${JSON.stringify(portData, null, 2)}`; saveData += `${itemDesc}${portData}` + `${i != len - 1 ? "," : ""}\n`; }); saveData += `}\nexport function api (id) {\n return { ...apiData[id] }\n}`; return saveData; } async function getItemFuncCode(idUrl, yapiConfig) { const { req_query, path, method, req_params, _id, title, catid } = await get( idUrl ).then((res) => res.data); const urlname = yapiConfig.urlname || "url"; const methodname = yapiConfig.methodname || "method"; const optionsname = yapiConfig.optionsname || "params"; const itemDesc = writeDescription([ `@description ${title} 接口id ${_id}`, `@description 文档地址 ${yapiConfig.host}/project/${yapiConfig.pid}/interface/api/${_id}`, `@param {object} ${optionsname} 请求需要的参数`, `@returns {object} ajax请求的参数`, ]); // 组装请求参数 let options = ""; if (req_query && req_query.length) { options += ` // 写在请求参数 Query中的参数会作为默认参数传入\n` + ` const defalut${optionsname} = {\n`; req_query.forEach((e, i) => { options += ` ${e.name}: ${ e.example ? "'" + e.example + "'" : "null" },\n`; }); options += ` }\n` + ` ${optionsname} = { ...defalut${optionsname}, ...${optionsname}}\n`; } let urlParams = ""; // 组装url请求参数 if (req_params && req_params.length) { let strreq_params = ""; let delString = ""; req_params.forEach((e, idx) => { strreq_params += `${e.name}${idx == req_params.length - 1 ? "" : ", "}`; delString += ` delete ${optionsname}['${e.name}']\n`; urlParams += `/\$\{${e.name}\}`; }); options += ` // 处理url参数\n` + ` const { ${strreq_params} } = ${optionsname}\n` + delString; } let reqConfig = ` {\n` + ` ${urlname}: \`${path.split("/{")[0]}${urlParams}\`,\n` + ` ${methodname}: '${method}',\n` + ` ${optionsname}\n ` + `}\n`; portData = `export const api_${catid}_${_id} = (${optionsname}) => {\n` + options + " return" + reqConfig + "}"; return `${itemDesc}${portData}`; } /** * @description 获取每个接口的信息的func * @param {Array} list 列表获取的item 数组 * @returns {string} 返回的文本 */ async function getApiDetailasFunc(list, yapiConfig) { const len = list.length; let saveData = ""; for (const key in list) { if (Object.hasOwnProperty.call(list, key)) { const e = list[key]; const idUrl = `${yapiConfig.host}/api/interface/get?token=${yapiConfig.token}&id=${e._id}`; const itemData = await getItemFuncCode(idUrl, yapiConfig); saveData += `${itemData}\n\n`; } } return saveData; } /** * 获取 yapi 列表数据 * @param {object} yapiConfig yapi配置 */ async function getYapiList(yapiConfig, dataType = "json", isgroup = false) { const listUrl = `${yapiConfig.host}/api/interface/list?limit=10000&project_id=${yapiConfig.pid}&token=${yapiConfig.token}`; // 从线上获取数据 const _objData = await get(listUrl) .then((res) => res.data) .catch((err) => {}); let groupData = null; if (isgroup) { groupData = {}; await _objData.list.forEach((e) => { if (groupData[e.catid]) { groupData[e.catid].push(e); } else { groupData[e.catid] = [e]; } }); } if (_objData.list && _objData.list.length) { let saveData = ""; if (dataType == "js") { if (groupData) { saveData = {}; for (const key in groupData) { if (Object.hasOwnProperty.call(groupData, key)) { const element = groupData[key]; if (yapiConfig.usefunc) { saveData[key] = await getApiDetailasFunc(element, yapiConfig); } else { saveData[key] = getApiDetailasDate(element, yapiConfig); } } } } else { if (yapiConfig.usefunc) { saveData = await getApiDetailasFunc(_objData.list, yapiConfig); } else { saveData = getApiDetailasDate(_objData.list, yapiConfig); } } } else { if (groupData) { saveData = {}; for (const key in groupData) { if (Object.hasOwnProperty.call(groupData, key)) { let _apidateJson = {}; const element = groupData[key]; element.forEach((e) => { _apidateJson[e._id] = { url: e.path.split("/{")[0], method: e.method, }; }); saveData[key] = `${JSON.stringify(_apidateJson, null, "\t")}`; } } } else { let _apidateJson = {}; _objData.list.forEach((e) => { _apidateJson[e._id] = { url: e.path.split("/{")[0], method: e.method, }; }); saveData = `${JSON.stringify(_apidateJson, null, "\t")}`; } } return { count: _objData.count, saveData }; } } module.exports = { getYapiList, };