service/request/index.ts
import axios from 'axios'
import type { AxiosInstance } from 'axios'
import { HealthRequestInterceptors, HealthRequestConfig } from './type'
import { ElLoading, ILoadingInstance } from 'element-plus'
const DEFAULT_LOADING = false
class HealthRequest {
instance: AxiosInstance
interceptors?: HealthRequestInterceptors
loading?: ILoadingInstance
showLoading: boolean
constructor(config: HealthRequestConfig) {
this.instance = axios.create(config)
this.interceptors = config.interceptors
this.showLoading = config.showLoading ?? true
// 从config中取出的拦截器是对应的实例的拦截器
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) => {
console.log('所有实例都有的拦截器: ', '请求成功的拦截')
if (this.showLoading) {
this.loading = ElLoading.service({
lock: true,
text: '正在加载中....',
background: 'rgba(0,0,0,0.5)'
})
}
return config
},
(err) => {
console.log('所有实例都有的拦截器: ', '请求失败的拦截')
return err
}
)
this.instance.interceptors.response.use(
(res) => {
console.log('所有实例都有的拦截器: ', '响应成功的拦截')
// 移除loading
this.loading?.close()
const data = res.data
if (data.returnCode === 1001) {
console.log('请求失败,错误信息')
} else {
return data
}
},
(err) => {
console.log('所有实例都有的拦截器: ', '响应失败的拦截')
// 移除loading
this.loading?.close()
// 判断不同的HttpErrorCode显示不同的错误信息
if (err.response.status === 404) {
console.log('404错误')
}
return err
}
)
}
request<T>(config: HealthRequestConfig): Promise<T> {
return new Promise<T>((resolve, reject) => {
// 1. 单个请求对请求config的处理
if (config.interceptors?.requestInterceptor) {
config = config.interceptors.requestInterceptor(config)
}
// 2. 判断是否显示loading
if (config.showLoading === false) {
this.showLoading = config.showLoading
}
this.instance
.request<any, T>(config)
.then((res) => {
// 1. 单个请求对数据的处理
if (config.interceptors?.responseInterceptor) {
res = config.interceptors?.responseInterceptor(res)
}
// 2. 将showloading设置true, 这样不会影响下一个请求
this.showLoading = DEFAULT_LOADING
// 3. 将结果resolve返回出去
resolve(res)
})
.catch((err) => {
// 将showloading设置true, 这样不会影响下一个请求
this.showLoading = DEFAULT_LOADING
reject(err)
})
})
}
get<T>(config: HealthRequestConfig): Promise<T> {
return this.request<T>({ ...config, method: 'GET' })
}
post<T>(config: HealthRequestConfig): Promise<T> {
return this.request<T>({ ...config, method: 'POST' })
}
delete<T>(config: HealthRequestConfig): Promise<T> {
return this.request<T>({ ...config, method: 'DELETE' })
}
put<T>(config: HealthRequestConfig): Promise<T> {
return this.request<T>({ ...config, method: 'PUT' })
}
}
export default HealthRequest