


An article explaining in detail how to dynamically generate API interfaces in the front end
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 -y
Initialize 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" }
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
- commander The
command
function provided by command can create sub-level commands. The options - 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.
- commander The description of the
description
command provided. The command - 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 update
Command
When 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.
Later, 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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools
