axios-interface
快速开始
yarn add axios-interface
GetStarted
基本用法
axios-interface 分为三个阶段:接口工厂 => 接口定义 => 接口调用,每个阶段传入的配置项都会覆盖前一阶段的同名配置项。
import {createFactory} from 'axios-interface';
const {createInterface} = createFactory(options);
const getUsers = createInterface('GET', '/rest/companies/{companyId}/users', options);
const getUsers = createInterface('GET', '/rest/companies/{companyId}/users', enhance, options);
const result = await getUsers(params);
配置 Options
interface Options extends AxiosRequestConfig {
onPending?: OnPending;
onResolve?: OnResolve;
onReject?: OnReject;
enhance?: Enhance;
interpolate?: RegExp;
disableWarning?: boolean;
encodePathVariable?: boolean;
transformDeleteParamsIntoBody?: boolean;
[whatever: string]: any;
}
type OnPending = <TParams>(params: TParams, options: Options) => Options | Promise<Options>;
type OnResolve = <TParams>(response: AxiosResponse, params: TParams, options: Options) => any;
type OnReject = <TParams>(response: AxiosError, params: TParams, options: Options) => any;
type Enhance = <TRequest extends (params: any, options?: Options) => Promise<any>>(
request: TRequest,
options: Options,
) => TRequest;
NOTE: 你可以使用 axios 的所有配置项
const {createInterface} = createFactory(options);
const getUsers = createInterface(method, urlTemplate, options);
const result = getUsers(params);
onPending, onResolve, onReject, enhance 的生命周期说明
-
没有 enhance 的状态下 request 的整个流程
函数 call => onPending => transformRequest(axios) => 浏览器 => transformResponse(axios) => onResolve | onReject => 函数返回
-
enhance() 是这个流程的外部包装
whatever_you_want_to_custom 的使用说明
你可以在任何时候,在 options 里注入你想要的数据,在 onPending, onResolve, onReject, enhance
四个钩子,都会把 options 重新给你,此时,你可以根据 options 处理多种情况
参数声明时机
-
以下参数仅在 createFactory 时声明有效
- interpolate,可以修改 urlTemplate 解析
-
以下参数在 createFactory 与 createInterface 时声明有效,request 时声明无效
- enhance, disableWarning, encodePathVariable
-
以下参数在 createFactory、 createInterface 和 request 时声明有效
- onPending, onResolve, onReject, transformDeleteParamsIntoBody
文档
Best Practice
FAQ
测试
yarn test
如何贡献
提交 PR
维护者
author: dancerphil
contributor: baidu efe team
讨论