新增
This commit is contained in:
@@ -0,0 +1,168 @@
|
||||
import axios, {
|
||||
AxiosError,
|
||||
type AxiosInstance,
|
||||
type AxiosRequestConfig,
|
||||
type AxiosResponse,
|
||||
type InternalAxiosRequestConfig
|
||||
} from 'axios'
|
||||
import { cloneDeep, isFunction, merge } from 'lodash'
|
||||
|
||||
import { RequestMethodsEnum } from '@/enums/requestEnums'
|
||||
|
||||
import axiosCancel from './cancel'
|
||||
import type { RequestData, RequestOptions } from './type'
|
||||
|
||||
export class Axios {
|
||||
private axiosInstance: AxiosInstance
|
||||
private readonly config: AxiosRequestConfig
|
||||
private readonly options: RequestOptions
|
||||
constructor(config: AxiosRequestConfig) {
|
||||
this.config = config
|
||||
this.options = config.requestOptions
|
||||
this.axiosInstance = axios.create(config)
|
||||
this.setupInterceptors()
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 获取axios实例
|
||||
*/
|
||||
getAxiosInstance() {
|
||||
return this.axiosInstance
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 设置拦截器
|
||||
*/
|
||||
setupInterceptors() {
|
||||
if (!this.config.axiosHooks) {
|
||||
return
|
||||
}
|
||||
const {
|
||||
requestInterceptorsHook,
|
||||
requestInterceptorsCatchHook,
|
||||
responseInterceptorsHook,
|
||||
responseInterceptorsCatchHook
|
||||
} = this.config.axiosHooks
|
||||
this.axiosInstance.interceptors.request.use(
|
||||
(config) => {
|
||||
this.addCancelToken(config)
|
||||
if (isFunction(requestInterceptorsHook)) {
|
||||
config = requestInterceptorsHook(config) as InternalAxiosRequestConfig
|
||||
}
|
||||
return config
|
||||
},
|
||||
(err: Error) => {
|
||||
if (isFunction(requestInterceptorsCatchHook)) {
|
||||
requestInterceptorsCatchHook(err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
)
|
||||
this.axiosInstance.interceptors.response.use(
|
||||
(response: AxiosResponse<RequestData>) => {
|
||||
this.removeCancelToken(response.config.url!)
|
||||
if (isFunction(responseInterceptorsHook)) {
|
||||
response = responseInterceptorsHook(response)
|
||||
}
|
||||
return response
|
||||
},
|
||||
(err: AxiosError) => {
|
||||
if (isFunction(responseInterceptorsCatchHook)) {
|
||||
responseInterceptorsCatchHook(err)
|
||||
}
|
||||
if (err.code != AxiosError.ERR_CANCELED) {
|
||||
this.removeCancelToken(err.config?.url!)
|
||||
}
|
||||
|
||||
if (err.code == AxiosError.ECONNABORTED || err.code == AxiosError.ERR_NETWORK) {
|
||||
return new Promise((resolve) => setTimeout(resolve, 500)).then(() =>
|
||||
this.retryRequest(err)
|
||||
)
|
||||
}
|
||||
return Promise.reject(err)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 添加CancelToken
|
||||
*/
|
||||
addCancelToken(config: AxiosRequestConfig) {
|
||||
const { ignoreCancelToken } = config.requestOptions
|
||||
!ignoreCancelToken && axiosCancel.add(config)
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 移除CancelToken
|
||||
*/
|
||||
removeCancelToken(url: string) {
|
||||
axiosCancel.remove(url)
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 重新请求
|
||||
*/
|
||||
retryRequest(error: AxiosError) {
|
||||
const config = error.config as any
|
||||
const { retryCount, isOpenRetry } = config.requestOptions
|
||||
if (!isOpenRetry || config.method?.toUpperCase() == RequestMethodsEnum.POST) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
config.retryCount = config.retryCount ?? 0
|
||||
|
||||
if (config.retryCount >= retryCount) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
config.retryCount++
|
||||
|
||||
return this.axiosInstance.request(config)
|
||||
}
|
||||
/**
|
||||
* @description get请求
|
||||
*/
|
||||
get<T = any>(
|
||||
config: Partial<AxiosRequestConfig>,
|
||||
options?: Partial<RequestOptions>
|
||||
): Promise<T> {
|
||||
return this.request({ ...config, method: RequestMethodsEnum.GET }, options)
|
||||
}
|
||||
|
||||
/**
|
||||
* @description post请求
|
||||
*/
|
||||
post<T = any>(
|
||||
config: Partial<AxiosRequestConfig>,
|
||||
options?: Partial<RequestOptions>
|
||||
): Promise<T> {
|
||||
return this.request({ ...config, method: RequestMethodsEnum.POST }, options)
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 请求函数
|
||||
*/
|
||||
request<T = any>(
|
||||
config: Partial<AxiosRequestConfig>,
|
||||
options?: Partial<RequestOptions>
|
||||
): Promise<any> {
|
||||
const opt: RequestOptions = merge({}, this.options, options)
|
||||
const axioxConfig: AxiosRequestConfig = {
|
||||
...cloneDeep(config),
|
||||
requestOptions: opt
|
||||
}
|
||||
const { urlPrefix } = opt
|
||||
// 拼接请求前缀如api
|
||||
if (urlPrefix) {
|
||||
axioxConfig.url = `${urlPrefix}${config.url}`
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
this.axiosInstance
|
||||
.request<any, AxiosResponse<RequestData<T>>>(axioxConfig)
|
||||
.then((res) => {
|
||||
resolve(res)
|
||||
})
|
||||
.catch((err) => {
|
||||
reject(err)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import axios, { type AxiosRequestConfig, type Canceler } from 'axios'
|
||||
|
||||
const cancelerMap = new Map<string, Canceler>()
|
||||
|
||||
// 获取一个唯一的请求键,它由请求的 URL 和参数组成
|
||||
function getRequestKey(config: AxiosRequestConfig): string {
|
||||
const { url, method, params, data } = config
|
||||
return [method, url, JSON.stringify(params), JSON.stringify(data)].join('&')
|
||||
}
|
||||
|
||||
export class AxiosCancel {
|
||||
private static instance?: AxiosCancel
|
||||
|
||||
static createInstance() {
|
||||
return this.instance ?? (this.instance = new AxiosCancel())
|
||||
}
|
||||
add(config: AxiosRequestConfig) {
|
||||
const requestKey = getRequestKey(config)
|
||||
this.remove(requestKey)
|
||||
config.cancelToken = new axios.CancelToken((cancel) => {
|
||||
if (!cancelerMap.has(requestKey)) {
|
||||
cancelerMap.set(requestKey, cancel)
|
||||
}
|
||||
})
|
||||
}
|
||||
remove(requestKey: string) {
|
||||
if (cancelerMap.has(requestKey)) {
|
||||
const cancel = cancelerMap.get(requestKey)
|
||||
cancel && cancel(requestKey)
|
||||
cancelerMap.delete(requestKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const axiosCancel = AxiosCancel.createInstance()
|
||||
|
||||
export default axiosCancel
|
||||
@@ -0,0 +1,128 @@
|
||||
import { AxiosError, type AxiosRequestConfig } from 'axios'
|
||||
import { merge } from 'lodash'
|
||||
import NProgress from 'nprogress'
|
||||
|
||||
import configs from '@/config'
|
||||
import { PageEnum } from '@/enums/pageEnum'
|
||||
import { ContentTypeEnum, RequestCodeEnum, RequestMethodsEnum } from '@/enums/requestEnums'
|
||||
import router from '@/router'
|
||||
|
||||
import { clearAuthInfo, getToken } from '../auth'
|
||||
import feedback from '../feedback'
|
||||
import { Axios } from './axios'
|
||||
import type { AxiosHooks } from './type'
|
||||
|
||||
// 处理axios的钩子函数
|
||||
const axiosHooks: AxiosHooks = {
|
||||
requestInterceptorsHook(config) {
|
||||
NProgress.start()
|
||||
const { withToken, isParamsToData } = config.requestOptions
|
||||
const params = config.params || {}
|
||||
const headers = config.headers || {}
|
||||
|
||||
// 添加token
|
||||
if (withToken) {
|
||||
const token = getToken()
|
||||
headers.token = token
|
||||
}
|
||||
// POST请求下如果无data,则将params视为data
|
||||
if (
|
||||
isParamsToData &&
|
||||
!Reflect.has(config, 'data') &&
|
||||
config.method?.toUpperCase() === RequestMethodsEnum.POST
|
||||
) {
|
||||
config.data = params
|
||||
config.params = {}
|
||||
}
|
||||
config.headers = headers
|
||||
return config
|
||||
},
|
||||
requestInterceptorsCatchHook(err) {
|
||||
NProgress.done()
|
||||
return err
|
||||
},
|
||||
async responseInterceptorsHook(response) {
|
||||
NProgress.done()
|
||||
const { isTransformResponse, isReturnDefaultResponse } = response.config.requestOptions
|
||||
|
||||
//返回默认响应,当需要获取响应头及其他数据时可使用
|
||||
if (isReturnDefaultResponse) {
|
||||
return response
|
||||
}
|
||||
// 是否需要对数据进行处理
|
||||
if (!isTransformResponse) {
|
||||
return response.data
|
||||
}
|
||||
const { code, data, show, msg } = response.data
|
||||
switch (code) {
|
||||
case RequestCodeEnum.SUCCESS:
|
||||
if (show) {
|
||||
msg && feedback.msgSuccess(msg)
|
||||
}
|
||||
return data
|
||||
case RequestCodeEnum.FAIL:
|
||||
if (show) {
|
||||
msg && feedback.msgError(msg)
|
||||
}
|
||||
return Promise.reject(data)
|
||||
case RequestCodeEnum.LOGIN_FAILURE:
|
||||
clearAuthInfo()
|
||||
router.push(PageEnum.LOGIN)
|
||||
return Promise.reject()
|
||||
case RequestCodeEnum.OPEN_NEW_PAGE:
|
||||
window.location.href = data.url
|
||||
return data
|
||||
case RequestCodeEnum.NOT_INSTALL:
|
||||
window.location.replace('/install/install.php')
|
||||
break
|
||||
default:
|
||||
return data
|
||||
}
|
||||
},
|
||||
responseInterceptorsCatchHook(error) {
|
||||
NProgress.done()
|
||||
if (error.code !== AxiosError.ERR_CANCELED) {
|
||||
error.message && feedback.msgError(error.message)
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
}
|
||||
|
||||
const defaultOptions: AxiosRequestConfig = {
|
||||
//接口超时时间
|
||||
timeout: configs.timeout,
|
||||
// 基础接口地址
|
||||
baseURL: configs.baseUrl,
|
||||
//请求头
|
||||
headers: { 'Content-Type': ContentTypeEnum.JSON, version: configs.version },
|
||||
// 处理 axios的钩子函数
|
||||
axiosHooks: axiosHooks,
|
||||
// 每个接口可以单独配置
|
||||
requestOptions: {
|
||||
// 是否将params视为data参数,仅限post请求
|
||||
isParamsToData: true,
|
||||
//是否返回默认的响应
|
||||
isReturnDefaultResponse: false,
|
||||
// 需要对返回数据进行处理
|
||||
isTransformResponse: true,
|
||||
// 接口拼接地址
|
||||
urlPrefix: configs.urlPrefix,
|
||||
// 忽略重复请求
|
||||
ignoreCancelToken: false,
|
||||
// 是否携带token
|
||||
withToken: true,
|
||||
// 开启请求超时重新发起请求请求机制
|
||||
isOpenRetry: true,
|
||||
// 重新请求次数
|
||||
retryCount: 2
|
||||
}
|
||||
}
|
||||
|
||||
function createAxios(opt?: Partial<AxiosRequestConfig>) {
|
||||
return new Axios(
|
||||
// 深度合并
|
||||
merge(defaultOptions, opt || {})
|
||||
)
|
||||
}
|
||||
const request = createAxios()
|
||||
export default request
|
||||
Vendored
+41
@@ -0,0 +1,41 @@
|
||||
import 'axios'
|
||||
|
||||
import type { AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
|
||||
|
||||
declare module 'axios' {
|
||||
// 扩展 RouteMeta
|
||||
interface AxiosRequestConfig {
|
||||
retryCount?: number
|
||||
axiosHooks?: AxiosHooks
|
||||
requestOptions: RequestOptions
|
||||
}
|
||||
}
|
||||
|
||||
export interface RequestOptions {
|
||||
isParamsToData: boolean
|
||||
isReturnDefaultResponse: boolean
|
||||
isTransformResponse: boolean
|
||||
urlPrefix: string
|
||||
ignoreCancelToken: boolean
|
||||
withToken: boolean
|
||||
isOpenRetry: boolean
|
||||
retryCount: number
|
||||
}
|
||||
|
||||
export interface AxiosHooks {
|
||||
requestInterceptorsHook?: (
|
||||
config: AxiosRequestConfig
|
||||
) => InternalAxiosRequestConfig | AxiosRequestConfig
|
||||
requestInterceptorsCatchHook?: (error: Error) => void
|
||||
responseInterceptorsHook?: (
|
||||
response: AxiosResponse<RequestData<T>>
|
||||
) => AxiosResponse<RequestData> | RequestData | T
|
||||
responseInterceptorsCatchHook?: (error: AxiosError) => void
|
||||
}
|
||||
|
||||
export interface RequestData<T = any> {
|
||||
code: number
|
||||
data: T
|
||||
msg: string
|
||||
show: boolean
|
||||
}
|
||||
Reference in New Issue
Block a user