1.0.3 • Published 7 months ago

@tuoyuan/gateway-request-lib v1.0.3

Weekly downloads
-
License
ISC
Repository
-
Last release
7 months ago

网关请求工具基础库

1. 简介

网关接口请求基础库,基于 axios 封装,支持动态注册 API、自定义勾子、全局消息、超时配置、自定义请求适配器等功能。

2. 安装

npm install @tuoyuan/gateway-request-lib

3. 使用

3.1 全局初始化请求工具实例

  • 调用init方法初始化请求工具实例且只能存在一个实例
import * as gatewayRequest from '@tuoyuan/gateway-request-lib';

// 初始化
gatewayRequest.init({
  /** 网关服务地址 */
  base_url: 'base_url',
  /** 应用ID */
  app_id: 'app_id',
  /** 应用KEY */
  app_key: 'app_key',
  /** 获取access_token方法 */
  getToken: () => {},
  // 更多配置见类型定义
});

3.2 封装 API 方法

  • 调用request方法封装 API 方法
import { request } from '@tuoyuan/gateway-request-lib';

export async function apiFunc() {
  return request<RequestData, ResponseData>({
    api: '/api/path',
    config: {
      access_token: true,
    },
  });
}

3.3 注册 API

  • 调用registerApis方法注册新的 api 方法,多次调用会进行深度合并,重复时会覆盖之前的 api 方法
import * as gatewayRequest from '@tuoyuan/gateway-request-lib';
import apis from 'your-apis-path';

// 注册API
gatewayTool.registerApis(apis);
  • 重写 TS 类型
// types.d.ts

declare module '@tuoyuan/gateway-request-lib' {
  import type * as GatewayTypes from '@tuoyuan/gateway-request-lib';
  import * as NewApis from 'your-apis-path';

  const init: GatewayTypes.GatewayTool['init'];
  const request: GatewayTypes.GatewayTool['request'];
  const registerApis: GatewayTypes.GatewayTool['registerApis'];
  const apis: GatewayTypes.MergeApiType<NewApis.IApis>;

  const Exports = {
    init,
    request,
    apis,
    registerApis,
  };
  export = Exports;
}

3.4 调用 API

import { apis } from '@tuoyuan/gateway-request-lib';

// 调用API
apis.apiFunc();
1.0.3

7 months ago

1.0.2

7 months ago

1.0.1

7 months ago