解决前端因后端接口迁移大量地方修改接口问题

发布时间:2024年01月17日

本来是想搞个开源项目,想想也没多少代码量就算了。

背景:后端接口项目迁移,前端很多项目要跟着一起改,特别繁琐。

我的想法: 所以项目接口都配置在一个系统里面,然后开发或者线上发布都自动生成一个接口文件,需要使用拿个接口直接引入使用就行。

脚本

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文件

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>;
}

文章来源:https://blog.csdn.net/qq_33715850/article/details/135652357
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。