import axios from "axios";
import type { AxiosRequestConfig, AxiosInstance, AxiosResponse } from "axios";
interface HJRequestInterceptors<T = AxiosResponse> {
requestInterceptor?: (config: AxiosRequestConfig) => AxiosRequestConfig;
requestInterceptorCatch?: (err: any) => any;
responseInterceptor?: (res: T) => T;
responseInterceptorCatch?: (err: any) => any;
}
interface HJRequestConfig<T = AxiosResponse> extends AxiosRequestConfig {
interceptors?: HJRequestInterceptors<T>;
}
class HJRequest {
instance: AxiosInstance;
interceptors?: HJRequestInterceptors;
constructor(config: HJRequestConfig) {
this.instance = axios.create(config);
this.interceptors = config.interceptors;
// 单个实例的拦截器
this.instance.interceptors.request.use(
this.interceptors?.requestInterceptor,
this.interceptors?.requestInterceptorCatch
);
this.instance.interceptors.response.use(
this.interceptors?.responseInterceptor,
this.interceptors?.responseInterceptorCatch
);
// 所有实例的拦截器
this.instance.interceptors.request.use(
config => {
return config;
},
err => err
);
this.instance.interceptors.response.use(
res => {
return res.data;
},
err => err
);
}
request<T>(config: HJRequestConfig<T>): Promise<T> {
return new Promise((resolve, reject) => {
if (config.interceptors?.requestInterceptor) {
config = config.interceptors.requestInterceptor(config);
}
this.instance.request<any, T>(config).then(res => {
if (config.interceptors?.responseInterceptor) {
res = config.interceptors.responseInterceptor(res);
}
resolve(res);
});
});
}
get<T>(config: HJRequestConfig<T>): Promise<T> {
return this.request({ ...config, method: "GET" });
}
post<T>(config: HJRequestConfig<T>): Promise<T>{
return this.request({ ...config, method: "POST" });
}
delete<T>(config: HJRequestConfig<T>): Promise<T> {
return this.request({ ...config, method: "DELETE" });
}
put<T>(config: HJRequestConfig<T>): Promise<T> {
return this.request({ ...config, method: "PATCH" });
}
}
export default HJRequest;
上一篇
手写Promise
手写Promise
2022-07-19
下一篇
数据结构 -- hash
hash
2022-07-07