mhy-http-ts
v1.0.2
Published
基于ts的axios二次封装
Downloads
1
Readme
Install
npm install mhy-http-ts
Usage
import type { AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios';
import { MethodEnum, ContentTypeEnum } from 'mhy-http-ts/enum';
import { Create as AxiosCreate, Canceler as AxiosCanceler, Retry as AxiosRetry } from 'mhy-http-ts';
const defaultRequestConfig: any = {
baseURL: '/api',
timeout: 10 * 1000,
headers: { 'Content-Type': ContentTypeEnum.JSON },
responseType: "json"
}
const defaultInterceptors: any = {
requestInterceptors: (config: AxiosRequestConfig, options?: any) => {
const token = ...;
const { withToken } = config || {};
if(withToken) {
config.headers.Authorization = token;
}
return config;
},
requestInterceptorsCatch: (error: AxiosError) => { ... },
responseInterceptors: (response: AxiosResponse<any>) => {
return response;
},
responseInterceptorsCatch: (error: AxiosError, instance: AxiosInstance) => {
const { config } = error || {};
const { method } = config || {};
// const retryRequest = new AxiosRetry();
// retryRequest.retry(instance, error);
return Promise.reject(error);
},
beforeRequestHook: (config: any) => {
const { method, params } = config || {};
if(method.toUpperCase() === MethodEnum.GET) {
...
} else {
...
}
return config;
},
afterRequestHook: (response: any) => {
const { data } = response || {};
const { code, } = data || {};
return code ? Promise.resolve(data) : Promise.reject(data);
},
requestCatchHook: (error: Error | AxiosError, config: AxiosRequestConfig) => {
return Promise.reject(error)
}
}
const defApi = new AxiosCreate(defaultRequestConfig, defaultInterceptors);
API
get
const getApi = defApi.get({
url: '/api/test/get',
params,
...
})
post
const postApi = defApi.post({
url: '/api/test/post',
data,
...
})
const download = defApi.post({
url: '/api/test/download',
data,
responseType: 'blob'
})
put
const putApi = defApi.post({
url: '/api/test/put',
data,
...
})
delete
const deleteApi = defApi.post({
url: '/api/test/delete',
data,
...
})
License
MIT