import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { AbortRequest } from './abort'
import { CustomRequest, InterceptorConfig } from './types'
export class CustomAxios<T> {
private instance: AxiosInstance
private abortRequest: AbortRequest
constructor(customRequest: CustomRequest<T>) {
this.instance = axios.create(customRequest.customConfig)
this.abortRequest = new AbortRequest()
this.useInterceptors(customRequest.interceptorConfig)
}
useInterceptors(config: InterceptorConfig<T>) {
const {
enableAbortRequest,
interceptorRequest,
interceptorRequestRejected,
interceptorResponse,
interceptorResponseRejected,
} = config
this.instance.interceptors.request.use(
(config: AxiosRequestConfig) => {
if (enableAbortRequest) {
const pendingKey = this.abortRequest.genPendingKey(config)
if (this.abortRequest.cancelRequest(pendingKey)) {
this.abortRequest.addPending(config)
}
}
if (interceptorRequest) {
return interceptorRequest(config)
}
return config
},
(error: any) => {
console.log('请求拦截器抛出异常...')
if (interceptorRequestRejected) {
return interceptorRequestRejected(error)
}
return Promise.reject(error)
}
)
this.instance.interceptors.response.use(
(response: AxiosResponse<T>) => {
if (enableAbortRequest) {
const pendingKey = this.abortRequest.genPendingKey(response.config)
this.abortRequest.removePending(pendingKey)
}
if (interceptorResponse) {
return interceptorResponse(response)
}
return response
},
(error) => {
console.log('响应拦截器抛出异常...')
if (interceptorResponseRejected) {
return interceptorResponseRejected(error)
}
return Promise.reject(error)
}
)
}
request(config: AxiosRequestConfig): Promise<AxiosResponse<T>> {
return new Promise((resolve, reject) => {
this.instance
.request(config)
.then((response) => {
resolve(response.data)
})
.catch((error) => {
const msg = error || '程序内部错误'
reject(msg)
})
})
}
get(url: string, params?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
return this.request({ url, method: 'GET', params, ...config })
}
post(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
return this.request({ url, method: 'POST', data, ...config })
}
put(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
return this.request({ url, method: 'PUT', data, ...config })
}
delete(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
return this.request({ url, method: 'DELETE', data, ...config })
}
}
console