亲宝软件园·资讯

展开

Typescript 封装 Axios

Sergio_ 人气:0

引言

对 axios 二次封装,更加的可配置化、扩展性更加强大灵活

通过 class 类实现,class 具备更强封装性(封装、继承、多态),通过实例化类传入自定义的配置

创建 class

严格要求实例化时传入的配置,拥有更好的代码提示

/**
 * @param {AxiosInstance} axios实例类型
 * @param {AxiosRequestConfig} axios配置项类型
 */
import type { AxiosInstance, AxiosRequestConfig } from 'axios'
class Http {
    axios: AxiosInstance
    constructor(config: AxiosRequestConfig) {
        // 创建一个实例 axios.create([config])
        this.axios = axios.create(config)
    }
}
// 每实例化一个 axios 时,都是不同的 axios 示例,互不干扰
new Http({
    baseURL:'qq.com';
    timeout:60 * 1
});
new Http({
    baseURL:'web.com'
});

axios.create([config])

const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});

AxiosRequestConfig 的类型注解

export interface AxiosRequestConfig<D = any> {
  url?: string;
  method?: Method | string;
  baseURL?: string;
  transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
  transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
  headers?: AxiosRequestHeaders;
  params?: any;
  paramsSerializer?: (params: any) => string;
  data?: D;
  timeout?: number;
  timeoutErrorMessage?: string;
  withCredentials?: boolean;
  adapter?: AxiosAdapter;
  auth?: AxiosBasicCredentials;
  responseType?: ResponseType;
  responseEncoding?: responseEncoding | string;
  xsrfCookieName?: string;
  xsrfHeaderName?: string;
  onUploadProgress?: (progressEvent: any) => void;
  onDownloadProgress?: (progressEvent: any) => void;
  maxContentLength?: number;
  validateStatus?: ((status: number) => boolean) | null;
  maxBodyLength?: number;
  maxRedirects?: number;
  beforeRedirect?: (options: Record<string, any>, responseDetails: {headers: Record<string, string>}) => void;
  socketPath?: string | null;
  httpAgent?: any;
  httpsAgent?: any;
  proxy?: AxiosProxyConfig | false;
  cancelToken?: CancelToken;
  decompress?: boolean;
  transitional?: TransitionalOptions;
  signal?: AbortSignal;
  insecureHTTPParser?: boolean;
  env?: {
    FormData?: new (...args: any[]) => object;
  };
}

封装 request(config)通用方法

/**
* axios#request(config)
* @param {*} config
* @returns {*}
*/
request(config: AxiosRequestConfig) {
    return this.axios.request(config)
}

加载全部内容

相关教程
猜你喜欢
用户评论