自动生成api.js文件

介绍

在项目开发中,通常前端需要和后端进行接口对接,常规操作步骤为:
1、打开后端接口文档地址
2、找到接口
3、复制接口
4、打开前端的api.js文件,赋值,并进行接口备注
在一个项目中,当有大量的接口时,就要重复多次的做这种事,大大影响开发效率。
而通过接口爬取的方式直接生成api.js文件将大大提升开发效率。

实现步骤

1、在src下的tool中新建api.js文件,主要用来实现对接口文档的接口爬取。主要利用node的request模块发起接口请求,fs模块进行写入操怍,具体实现如下:

const fs = require('fs')
const request = require('request')
const config = require('../config.js')
let str = ``

let obj = {}

for (let key in config.API_URL) {
  const API_DOC_URL = `${config.API_URL[key]}/operation/v2/api-docs` // 接口文档地址
  const API_DOC_URL1 = `${config.API_URL[key]}/v2/api-docs` // 接口文档地址
  sendRequest(API_DOC_URL, key)
  sendRequest(API_DOC_URL1, key)
}
function sendRequest(url, key) {
  request(url, (error, response, body) => {
    if (!error && response.statusCode == 200) {
      let apiListObj = JSON.parse(`${body}`).paths // 接口地址对象(当前文档所有的接口地址都在这个对象里)
      for (let i in apiListObj) {
        let name = i.split('/').join('_')

        if (obj[name]) {
          continue
        }

        if (apiListObj[i].post) {
          str += `  "${name}": '/${key}${i}', // ${apiListObj[i].post.summary}\n`
        } else if (apiListObj[i].get) {
          str += `  "${name}": '/${key}${i}', // ${apiListObj[i].get.summary}\n`
        } else if (apiListObj[i].put) {
          str += `  "${name}": '/${key}${i}', // ${apiListObj[i].put.summary}\n`
        } else if (apiListObj[i].delete) {
          str += `  "${name}": '/${key}${i}', // ${apiListObj[i].delete.summary}\n`
        }

        obj[name] = true
      }
    }
    // 如果是最后一个接口,则写入
    writeFile(str)
  })
}
function writeFile(str) {
  // 去除最后一个逗号
  // var r = /,+$/;
  str = str.replace(/,([^,]*?)$/g, `$1`)
  fs.writeFile(
    './src/apis.js',
    `import megreApi from '@companyfe/szty-frame/src/utils/megreAPI'
    let mergedApi = megreApi({
			${str}})
			
			let apis = {}
			let publicPath = process.env.BASE_URL || '/'
			
			// 清除尾部的斜杠
			if ('/' == publicPath[publicPath.length - 1]) {
			  publicPath = publicPath.slice(0, publicPath.length - 1)
			}
			
			for (let key in mergedApi) {
			  apis[key] = publicPath + mergedApi[key]
			}
			
			export default apis
			`,
    err => {
      if (err) throw err
      // console.log('写入完成')
    }
  )
}

在congfig.js中主要是定义一些配置文件,如用到的API_URL,这里考虑到多个地址的情况

module.exports = {
	API_URL: {
	    file: 'http://aaa/file', // 文件服务接口地址
	    dict: 'http:/bbb/dict', // 字典表接口地址
	    staticfile: 'http://ccc/staticfile' // 静态文件
	}
}

2、在package.json 文件中定义运行脚本命令,"api": "node src/tool/api.js",

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JS API 接口接收与返回 是一个轻型的、安全的、跨网际的、跨语言的、跨平台的、跨环境的、跨域的、支持复杂对象传输的、支持引用参数传递的、支持内容输出重定向的、支持分级错误处理的、支持会话的、面向服务的高性能远程过程调用协议。 该版本直接解压后就可以使用,其中 属于公共文件。不论是客户端还是服务器端都需要这些文件。 是客户端文件,如果你只需要使用客户端,那么只要有上面那些公共文件和这个文件就可以使用了,使用时,直接在你的程序中包含 phprpc_client.php 就可以,公共文件不需要单独包含。 这三个文件是服务器端需要的文件。 其中 dhparams 目录中包含的是加密传输时用来生成密钥的参数 dhparams.php 是用来读取 dhparams 目录中文件的类。 phprpc_server.php 是服务器端,如果你要使用 PHP 来发布 PHPRPC 服务,只需要包含这个文件就可以了。公共文件和 dhparams.php 都不需要单独包含。 PHP 4.3+、PHP 5、PHP 6 客户端要求开启 socket 扩展。 服务器端需要有 IIS、Apache、lighttpd 等可以运行 PHP 程序的 Web 服务器。 如果服务器端需要加密传输的能力,必须要保证 session 配置正确。 <?php include('php/phprpc_server.php'); //加载文件 function hello($name) { return'Hello ' . $name; } $server = new PHPRPC_Server(); //创建服务端 $server->add(array('hello', 'md5', 'sha1')); //数组形式一次注册多个函数 $server->add('trim'); //单一注册 $server->start(); //开启服务 ?> <?php include ("php/phprpc_client.php"); //加载文件 $client = new PHPRPC_Client('http://127.0.0.1/server.php'); //创建客户端 并连接服务端文件 echo$client->Hello("word"); //调用方法 返回 hello word ?> -------------------------------------------------- --------------------------------------------------- ------------------------------ 服务端其他说明: <?php include('php/phprpc_server.php'); //加载文件 function hello($name) { return'Hello ' . $name; } class Example1 { staticfunction foo() { return'foo'; } function bar() { return'bar'; } } $server = new PHPRPC_Server(); //创建服务端 $server->add('foo', 'Example1'); //静态方法直接调用 $server->add('bar', new Example1()); //非静态方法 需要实例化 //注册别名调用 $server->add('hello', NULL, 'hi'); //第三参数是函数的别名 客户端通过别名来调用函数 $server->add('foo', 'Example1', 'ex1_foo'); $server->add('bar', new Example1(), 'ex1_bar'); $server->setCharset('UTF-8'); //设置编码 $server->setDebugMode(true); //打印错误 $server->setEnableGZIP(true); //启动压缩输出虽然可以让传输的数据量减少,但是它会占用更多的内存和 CPU,因此它默认是关闭的。 $server->start(); //开启服务 ?> -------------------------------------------------- --------------------------------------------------- --------------------------- 客户端其他说明: <?php include ("php/phprpc_client.php"); $client = new PHPRPC_Client(); $client->useService('http://127.0.0.1/server.php'); //远程调用地址 $client->setKeyLength(1000); //密钥长度 $client->setEncryptMode(3); //加密等级0-3 $client->setCharset('UTF-8'); //设置编码 $client->setTimeout(10); //设置超时时间 echo$client->hi('PHPRPC'), "\r\n"; //调用函数 echo$client->getKeyLength(), "\r\n"; //下面是返回值 echo$client->getEncryptMode(), "\r\n"; echo$client->getCharset(), "\r\n"; echo$client->getTimeout(), "\r\n"; ?> -------------------------------------------------- --------------------------------------------------- ---------------------- 关于session <?php include('php/phprpc_server.php'); class ExampleCounter { function ExampleCounter() { if (!isset($_SESSION['count'])) { $_SESSION['count'] = 0; } } function inc() { $_SESSION['count'] += 1; } functioncount() { return$_SESSION['count']; } } $server = new PHPRPC_Server(); $server->add(array('inc', 'count'), new ExampleCounter()); $server->start(); ?> <?php include("php/phprpc_client.php"); $client = newPHPRPC_Client(); $client->useService('http://127.0.0.1/1.php'); $client->setTimeout(10); echo $client->inc(); echo $client->count(); echo $client->inc(); echo $client->count(); ?> 每次刷新都是新建的client 服务端并不能识别.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值