T封装axios
import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
interface TRequestInterceptors<T = AxiosResponse> {
requestInterceptor?: (config: AxiosRequestConfig) => AxiosRequestConfig
requestInterceptorCache?: (error: any) => any
responseInterceptor?: (res: T) => T
responseInterceptorCache?: (error: any) => any
}
interface TRequestConfig<T = AxiosResponse> extends AxiosRequestConfig {
interceptors?: TRequestInterceptors<T>
}
class TRequest {
instance: AxiosInstance
interceptors?: TRequestInterceptors
constructor(config: TRequestConfig) {
this.instance = axios.create(config)
this.interceptors = config.interceptors
this.instance.interceptors.request.use(
this.interceptors?.requestInterceptor,
this.interceptors?.requestInterceptorCache
)
this.instance.interceptors.response.use(
this.interceptors?.responseInterceptor,
this.interceptors?.responseInterceptorCache
)
this.instance.interceptors.request.use(
(config) => {
console.log('所有的实例都有的拦截器:请求成功')
return config.data
},
(err) => {
console.log('所有的实例都有的拦截器:请求失败')
return err
}
)
this.instance.interceptors.response.use(
(res) => {
console.log('所有的实例都有的拦截器:响应成功')
return res.data
},
(err) => {
console.log('所有的实例都有的拦截器:响应失败')
return err
}
)
}
request<T>(config: TRequestConfig<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)
})
.catch((err) => {
reject(err)
})
})
}
get<T>(config: TRequestConfig<T>): Promise<T> {
return this.request({ ...config, method: 'GET' })
}
post<T>(config: TRequestConfig<T>): Promise<T> {
return this.request({ ...config, method: 'POST' })
}
patch<T>(config: TRequestConfig<T>): Promise<T> {
return this.request({ ...config, method: 'PATCH' })
}
delete<T>(config: TRequestConfig<T>): Promise<T> {
return this.request({ ...config, method: 'DELETE' })
}
}
export default TRequest