Home  >  Article  >  Web Front-end  >  An article explaining in detail how to dynamically generate API interfaces in the front end

An article explaining in detail how to dynamically generate API interfaces in the front end

藏色散人
藏色散人forward
2023-01-31 16:35:182578browse

This article brings you relevant knowledge about the front-end, which mainly introduces how to dynamically generate API interfaces in the front-end. Let's take a look at it together. I hope it will be helpful to everyone.

In the era of ts rampant, interface request and return parameter definition types have become a cumbersome thing. In this case, we can use node services to automate construction

1 Build custom commands

1.1 Build the project

Create the APISDK folder, enter the folder, and run the commandnpm init -yInitialize the package.json file

Add the following code to the package.json file to tell package.json that the file executed by my bin called api-test is apiSdk.js

//package.json文件
"bin":{
    "api-test": "apiSdk.js"
  }

An article explaining in detail how to dynamically generate API interfaces in the front end

1.2 Commander.js

InstallationCommander.js Complete solution for node.js command line interface, inspired by Ruby Commanderinspired.

For specific APIs, you can go directly to learn

The necessary skills for front-end development node cli.

//install 安装命令
npm install commander

Create the apiSdk.js file in the APISDK folder and write the following code

#!/usr/bin/env node
"use strict";

var commander_1 = require("commander");
commander_1.program.name('api-test');
commander_1.program
    .command('init') // 创建命令
    .option('--json2js', '配置文件 json 转 js') // 该命令相关的选项配置
    .description('初始化配置文件') // 命令的描述
    .action(function (d, otherD,cmd) { //处理子级命令
        console.log('我是init')
	});
commander_1.program
    .command('update') // 创建命令
    .option('--json2js', '配置文件 json 转 js') // 该命令相关的选项配置
    .description('初始化配置文件') // 命令的描述
    .action(function (d, otherD,cmd) { //处理子级命令
        console.log('我是update')
	});
commander_1.program.parse(process.argv);

#!/usr/bin/env node The meaning of this paragraph It is an interpreter that allows you to use node for scripting. Then you can use the syntax of node as follows

  1. commander The command function provided by command can create sub-level commands. The
  2. options
  3. options provided by commander can quickly define command line parameters and generate corresponding parameter configuration documents for display in the --help command. options can receive multiple parameters.
  4. commander The description of the description command provided. The
  5. command
  6. provided by commander handles child commands.

Enter the npm link command in the APISDK folder terminal (when developing npm packages locally, we can use the npm link command to link the npm package to The module is linked to the running project to easily debug and test the module), then we create a new folder outside the APISDK folder and run api-test init and api -test updateCommand

An article explaining in detail how to dynamically generate API interfaces in the front endWhen we enter the corresponding command, the method in the action will be executed.

Second, dynamically generate the corresponding api

Add the utils/command.js and utils/http.js files in the APISDK folder

//文件目录
|- APISDK
   |- node_modules
   |- utils
      |- command.js
      |- http.js
   |- apiSdk.js
   |- package-lock.json
   |- package.json
//command.js文件
var path=require("path");
 /** 默认配置文件名 */
var DEFAULT_CONFIG_FILENAME = 'apiSdk.config.json';

var {http} =  require('./http.js')
var fs = require("fs");
/** 默认配置文件模版 */
var INITIAL_CONFIG = {
    outDir: 'src/api',
    services: {},
};

function writeConfigFile(filename, content) {
    fs.writeFileSync(filename, JSON.stringify(content, null, 4));
    
}
// 递归创建目录 同步方法
function mkdirsSync(dirname) {
    if (fs.existsSync(dirname)) {
      return true;
    } else {
      if (mkdirsSync(path.dirname(dirname))) {
        fs.mkdirSync(dirname);
        return true;
      }
    }
}
const BamConfig = {
    /** 初始化 */
    init:function (configFilename, content) {
        
        var f = fs.existsSync(DEFAULT_CONFIG_FILENAME);
        if (!f) {
            throw new Error("already has ".concat(f));
        }
        writeConfigFile(DEFAULT_CONFIG_FILENAME, INITIAL_CONFIG);
        return configFilename;
    },
    update:function (configFilename, content) {
        //判断当前文件是否存在
        var f = fs.existsSync(DEFAULT_CONFIG_FILENAME);
    console.log('f',fs)
        // 同步读取文件数据
        var data =  fs.readFileSync(DEFAULT_CONFIG_FILENAME);
        
        //解析当前文件内容
        var str = JSON.parse(data.toString())
        console.log('str',str)
        //同步递归创建文件夹
        mkdirsSync(str.outDir)
    
        //配置模版整合需要写入的内容
        var api =   http.map(item=>{
            var name = item.url.split('/').reverse()[0]
            return `//测试接口 ${name} \n export const ${name} = axios.request( '${item.url}' , '${item.method}', params )`
        })
        //进行写入
        fs.writeFileSync(`${str.outDir}/http.js`, api.join('\n\n'));
    
        //替换掉默认配置文件路径,组装好进行写入
        INITIAL_CONFIG.outDir = str.outDir
        var apis = http.map(item=>`${item.method} ${item.url}`)
        INITIAL_CONFIG.apis = apis
        writeConfigFile(DEFAULT_CONFIG_FILENAME, INITIAL_CONFIG);
        return configFilename;
    }
}
exports.bamCommand = {
    init:function(option){
        BamConfig.init()
    },
    update:function(option){
        BamConfig.update()
    },
}
//http.js文件
exports.http = [{
    url:'localhost:8888/aa/bb/aa',
    method:'Get',
},{
    url:'localhost:8888/aa/bb/bb',
    method:'POST',
},{
    url:'localhost:8888/aa/bb/cc',
    method:'Get',
},{
    url:'localhost:8888/aa/bb/dd',
    method:'Get',
},]

Rewrite the apiSdk.js file, The change is to introduce the command.js above and execute the corresponding command in the action

#!/usr/bin/env node
"use strict";
var command = require("./utils/command");
var commander_1 = require("commander");
commander_1.program.name('api-test');
commander_1.program
    .command('init')
    .option('--json2js', '配置文件 json 转 js')
    .description('初始化配置文件')
    .action(function (d, otherD,cmd) {
        console.log('我是init')
        command.bamCommand.init()
	});
    console.log('command',command)
commander_1.program
    .command('update')
    .option('--json2js', '配置文件 json 转 js')
    .description('更新文件')
    .action(function (d, otherD,cmd) {
        console.log('我是update')
        command.bamCommand.update()
	});
commander_1.program.parse(process.argv);

http.js is to simulate the back-end interface data. When the code platform is unified, we can replace it with the interface to obtain all Interfaces and corresponding parameters are used for deeper writing, such as the request and return type parameters of the interface. Re-run the api-test init and api-test update commands, apiSdk.config.json is written into apis (apis stores all interface simple information, and there are different interfaces in the backend When serving, we can similarly obtain all interface service generation configuration information based on the interface and generate api), and src/api/http.js will generate the corresponding interface based on the template.

An article explaining in detail how to dynamically generate API interfaces in the front endAn article explaining in detail how to dynamically generate API interfaces in the front endLater, we can package the APISDK into an SDK according to the rules. [Recommended learning: web front-end development]

The above is the detailed content of An article explaining in detail how to dynamically generate API interfaces in the front end. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete