|
@@ -6,6 +6,10 @@ import type { AxiosResponse, AxiosRequestConfig } from 'axios'
|
|
|
export type ResErrorHandler = <D, T extends ResData<D>>(response: AxiosResponse<T>, data?: T) => void
|
|
|
export type ReqErrorHandler = <T>(err: Error, response: AxiosRequestConfig<T>) => void
|
|
|
export type ResData<T> = { code: ResCode, message: string, data: T }
|
|
|
+export type Hook = {
|
|
|
+ before: (config: AxiosRequestConfig) => void
|
|
|
+ after: (config: AxiosRequestConfig) => void
|
|
|
+}
|
|
|
|
|
|
export const axiosFactory = () => {
|
|
|
const axiosRaw = Axios.create()
|
|
@@ -16,6 +20,8 @@ export const axiosFactory = () => {
|
|
|
unResErrorSet: [] as string[],
|
|
|
resErrorHandler: [] as ResErrorHandler[],
|
|
|
reqErrorHandler: [] as ReqErrorHandler[],
|
|
|
+ unLoadingSet: [] as string[],
|
|
|
+ hook: [] as Hook[]
|
|
|
}
|
|
|
|
|
|
|
|
@@ -97,6 +103,12 @@ export const axiosFactory = () => {
|
|
|
del: delUnsetResErrorURLS
|
|
|
} = getExponseApi('unResErrorSet')
|
|
|
|
|
|
+ const {
|
|
|
+ set: setHook,
|
|
|
+ add: addHook,
|
|
|
+ del: delHook
|
|
|
+ } = getExponseApi('hook')
|
|
|
+
|
|
|
const setDefaultURI = (url: string) => {
|
|
|
axiosRaw.defaults.baseURL = url
|
|
|
}
|
|
@@ -114,6 +126,10 @@ export const axiosFactory = () => {
|
|
|
|
|
|
axiosRaw.interceptors.request.use(
|
|
|
config => {
|
|
|
+ for (const hook of axiosConfig.hook) {
|
|
|
+ hook.before(config)
|
|
|
+ }
|
|
|
+
|
|
|
if (!matchURL(axiosConfig.unTokenSet, config)) {
|
|
|
if (!axiosConfig.token) {
|
|
|
if (!matchURL(axiosConfig.unReqErrorSet, config)) {
|
|
@@ -134,6 +150,10 @@ export const axiosFactory = () => {
|
|
|
|
|
|
axiosRaw.interceptors.response.use(
|
|
|
(response: AxiosResponse<ResData<any>>) => {
|
|
|
+ for (const hook of axiosConfig.hook) {
|
|
|
+ hook.after(response.config)
|
|
|
+ }
|
|
|
+
|
|
|
if (matchURL(axiosConfig.unResErrorSet, response.config)) {
|
|
|
return response
|
|
|
}
|
|
@@ -152,6 +172,9 @@ export const axiosFactory = () => {
|
|
|
}
|
|
|
},
|
|
|
(err) => {
|
|
|
+ for (const hook of axiosConfig.hook) {
|
|
|
+ hook.after(err.config)
|
|
|
+ }
|
|
|
if (!matchURL(axiosConfig.unResErrorSet, err.config)) {
|
|
|
callErrorHandler('res', err.response)
|
|
|
}
|
|
@@ -202,7 +225,10 @@ export const axiosFactory = () => {
|
|
|
setUnsetResErrorURLS,
|
|
|
addUnsetResErrorURLS,
|
|
|
delUnsetResErrorURLS,
|
|
|
- setDefaultURI
|
|
|
+ setDefaultURI,
|
|
|
+ setHook,
|
|
|
+ addHook,
|
|
|
+ delHook,
|
|
|
}
|
|
|
}
|
|
|
|