本来是想搞个开源项目,想想也没多少代码量就算了。
背景:后端接口项目迁移,前端很多项目要跟着一起改,特别繁琐。
我的想法: 所以项目接口都配置在一个系统里面,然后开发或者线上发布都自动生成一个接口文件,需要使用拿个接口直接引入使用就行。
脚本文章来源:https://www.toymoban.com/news/detail-801068.html
const http = require('https');
const fs = require('fs');
const { exec } = require('child_process');
const configPath = './src/service.ts';
const env = process.argv[2] || 'product';
function httpRequest(url, method, headers, data) {
return new Promise((resolve, reject) => {
const options = {
method: method,
headers: headers,
};
const request = http.request(url, options, (response) => {
let responseData = '';
response.on('data', (chunk) => {
responseData += chunk;
});
response.on('end', () => {
resolve(responseData);
});
});
request.on('error', (error) => {
reject(error);
});
if (data) {
request.write(data);
}
request.end();
});
}
function writeFile() {
const list = [
{
name: 'getInfoList',
url: '/demo/nurse/white-list/query',
remark: 'demo查询',
params: "a:'111',b:new Date().getTime(),",
commonParams: {
name: 'commonParams',
value: `{operator: 'demo',requestSystem: 'demo',traceLogId: new Date().getTime(),}`,
},
},
{
name: 'addInfo',
url: '/demo/nurse/add',
remark: 'demo新增',
},
];
let common = {};
list.forEach((item) => {
const { commonParams } = item;
if (commonParams && !common[commonParams.name]) {
common[commonParams.name] = commonParams.value;
}
});
let commonText = '';
Object.entries(common).forEach(([key, value]) => {
commonText += `const ${key}= ${value}`;
});
let content = '';
content = list
.map((item) => {
const remarkText = `\n/**\n * ${item.remark}\n * @param {*} params\n * @returns\n */\n`;
return `${env === 'dev' ? remarkText : ''}export async function ${
item.name
}(params?: RequestType):Promise<ResponseType>{const res = await request('${
item.url
}', {...params,${item.commonParams ? `...${item.commonParams.name},` : ''}${
item.params ? item.params : ''
}});return res as Promise<ResponseType>;}`;
})
.join('\n');
fs.appendFileSync(configPath, commonText + content);
if (env === 'dev') {
//格式化文件内容
exec(`prettier --write "${configPath}"`, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
}
}
//生成本地配置文件
function initServiceConfig() {
fs.writeFileSync(
configPath,
`import { request } from '@umijs/max';;type ResponseType = any;type RequestType = any; \n`,
);
writeFile();
}
async function main() {
try {
// const data = await httpRequest(
// 'https://jsonplaceholder.typicode.com/todos/1',
// 'GET',
// {},
// null,
// );
initServiceConfig();
} catch (error) {
console.error(error);
initServiceConfig();
}
}
main();
生成的servie.ts文件文章来源地址https://www.toymoban.com/news/detail-801068.html
import { request } from '@umijs/max';
type ResponseType = any;
type RequestType = any;
const commonParams = { operator: 'demo', requestSystem: 'demo', traceLogId: new Date().getTime() };
/**
* demo查询
* @param {*} params
* @returns
*/
export async function getInfoList(params?: RequestType): Promise<ResponseType> {
const res = await request('/demo/nurse/white-list/query', {
...params,
...commonParams,
a: '111',
b: new Date().getTime(),
});
return res as Promise<ResponseType>;
}
/**
* demo新增
* @param {*} params
* @returns
*/
export async function addInfo(params?: RequestType): Promise<ResponseType> {
const res = await request('/demo/nurse/add', { ...params });
return res as Promise<ResponseType>;
}
到了这里,关于解决前端因后端接口迁移大量地方修改接口问题的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!