fix: axios

pull/40/MERGE
xingyu 2023-11-07 09:20:10 +08:00
parent 78ebcb15d5
commit bd773ff843
7 changed files with 62 additions and 16 deletions

View File

@ -11,7 +11,7 @@ const DEFAULT_CONFIG: TreeHelperConfig = {
pid: 'pid', pid: 'pid',
} }
// 获取配置 Object.assign 从一个或多个源对象复制到目标对象 // 获取配置 Object.assign 从一个或多个源对象复制到目标对象
const getConfig = (config: Partial<TreeHelperConfig>) => Object.assign({}, DEFAULT_CONFIG, config) const getConfig = (config: Partial<TreeHelperConfig>) => Object.assign({}, DEFAULT_CONFIG, config)
// tree from list // tree from list

View File

@ -1,4 +1,10 @@
import type { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios' import type {
AxiosError,
AxiosInstance,
AxiosRequestConfig,
AxiosResponse,
InternalAxiosRequestConfig,
} from 'axios'
import axios from 'axios' import axios from 'axios'
import qs from 'qs' import qs from 'qs'
import { cloneDeep } from 'lodash-es' import { cloneDeep } from 'lodash-es'
@ -12,6 +18,7 @@ import { useGlobSetting } from '@/hooks/setting'
import { getRefreshToken, getTenantId, setAccessToken } from '@/utils/auth' import { getRefreshToken, getTenantId, setAccessToken } from '@/utils/auth'
export * from './axiosTransform' export * from './axiosTransform'
const globSetting = useGlobSetting() const globSetting = useGlobSetting()
// 请求队列 // 请求队列
let requestList: any[] = [] let requestList: any[] = []
@ -77,6 +84,7 @@ export class VAxios {
* @description: Interceptor configuration * @description: Interceptor configuration
*/ */
private setupInterceptors() { private setupInterceptors() {
// const transform = this.getTransform();
const { const {
axiosInstance, axiosInstance,
options: { transform }, options: { transform },
@ -84,13 +92,20 @@ export class VAxios {
if (!transform) if (!transform)
return return
const { requestInterceptors, requestInterceptorsCatch, responseInterceptors, responseInterceptorsCatch } = transform const {
requestInterceptors,
requestInterceptorsCatch,
responseInterceptors,
responseInterceptorsCatch,
} = transform
const axiosCanceler = new AxiosCanceler() const axiosCanceler = new AxiosCanceler()
// 请求拦截器配置处理 // 请求拦截器配置处理
this.axiosInstance.interceptors.request.use((config: InternalAxiosRequestConfig) => { this.axiosInstance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
const requestOptions = (config as unknown as any).requestOptions ?? this.options.requestOptions // If cancel repeat request is turned on, then cancel repeat request is prohibited
const requestOptions
= (config as unknown as any).requestOptions ?? this.options.requestOptions
const ignoreCancelToken = requestOptions?.ignoreCancelToken ?? true const ignoreCancelToken = requestOptions?.ignoreCancelToken ?? true
!ignoreCancelToken && axiosCanceler.addPending(config) !ignoreCancelToken && axiosCanceler.addPending(config)
@ -177,6 +192,7 @@ export class VAxios {
if (params.filename) if (params.filename)
formData.append(customFilename, params.file, params.filename) formData.append(customFilename, params.file, params.filename)
else else
formData.append(customFilename, params.file) formData.append(customFilename, params.file)

View File

@ -10,7 +10,7 @@ export class AxiosRetry {
*/ */
retry(axiosInstance: AxiosInstance, error: AxiosError) { retry(axiosInstance: AxiosInstance, error: AxiosError) {
const { config } = error.response const { config } = error.response
const { waitTime, count } = config?.requestOptions?.retryRequest const { waitTime, count } = config?.requestOptions?.retryRequest ?? {}
config.__retryCount = config.__retryCount || 0 config.__retryCount = config.__retryCount || 0
if (config.__retryCount >= count) if (config.__retryCount >= count)
return Promise.reject(error) return Promise.reject(error)

View File

@ -1,7 +1,12 @@
/** /**
* Data processing class, can be configured according to the project * Data processing class, can be configured according to the project
*/ */
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios' import type {
AxiosInstance,
AxiosRequestConfig,
AxiosResponse,
InternalAxiosRequestConfig,
} from 'axios'
import type { RequestOptions, Result } from '@/types/axios' import type { RequestOptions, Result } from '@/types/axios'
export interface CreateAxiosOptions extends AxiosRequestConfig { export interface CreateAxiosOptions extends AxiosRequestConfig {
@ -29,7 +34,10 @@ export abstract class AxiosTransform {
/** /**
* @description: * @description:
*/ */
requestInterceptors?: (config: InternalAxiosRequestConfig, options: CreateAxiosOptions) => InternalAxiosRequestConfig requestInterceptors?: (
config: InternalAxiosRequestConfig,
options: CreateAxiosOptions,
) => InternalAxiosRequestConfig
/** /**
* @description: * @description:

View File

@ -9,9 +9,14 @@ import projectSetting from '@/settings/projectSetting'
import { SessionTimeoutProcessingEnum } from '@/enums/appEnum' import { SessionTimeoutProcessingEnum } from '@/enums/appEnum'
const { createMessage, createErrorModal } = useMessage() const { createMessage, createErrorModal } = useMessage()
const error = createMessage.error!
const stp = projectSetting.sessionTimeoutProcessing const stp = projectSetting.sessionTimeoutProcessing
export function checkStatus(status: number, msg: string, errorMessageMode: ErrorMessageMode = 'message'): void { export function checkStatus(
status: number,
msg: string,
errorMessageMode: ErrorMessageMode = 'message',
): void {
const { t } = useI18n() const { t } = useI18n()
const userStore = useUserStoreWithOut() const userStore = useUserStoreWithOut()
let errMessage = '' let errMessage = ''
@ -28,6 +33,7 @@ export function checkStatus(status: number, msg: string, errorMessageMode: Error
errMessage = msg || t('sys.api.errMsg401') errMessage = msg || t('sys.api.errMsg401')
if (stp === SessionTimeoutProcessingEnum.PAGE_COVERAGE) if (stp === SessionTimeoutProcessingEnum.PAGE_COVERAGE)
userStore.setSessionTimeout(true) userStore.setSessionTimeout(true)
else else
userStore.logout(true) userStore.logout(true)
@ -69,7 +75,8 @@ export function checkStatus(status: number, msg: string, errorMessageMode: Error
if (errMessage) { if (errMessage) {
if (errorMessageMode === 'modal') if (errorMessageMode === 'modal')
createErrorModal({ title: t('sys.api.errorTip'), content: errMessage }) createErrorModal({ title: t('sys.api.errorTip'), content: errMessage })
else if (errorMessageMode === 'message') else if (errorMessageMode === 'message')
createMessage.error({ content: errMessage, key: `global_error_message_status_${status}` }) error({ content: errMessage, key: `global_error_message_status_${status}` })
} }
} }

View File

@ -2,7 +2,10 @@ import { isObject, isString } from '@/utils/is'
const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss' const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss'
export function joinTimestamp<T extends boolean>(join: boolean, restful: T): T extends true ? string : object export function joinTimestamp<T extends boolean>(
join: boolean,
restful: T,
): T extends true ? string : object
export function joinTimestamp(join: boolean, restful = false): string | object { export function joinTimestamp(join: boolean, restful = false): string | object {
if (!join) if (!join)

View File

@ -72,6 +72,7 @@ const transform: AxiosTransform = {
if (options.successMessageMode === 'modal') if (options.successMessageMode === 'modal')
createSuccessModal({ title: t('sys.api.successTip'), content: successMsg }) createSuccessModal({ title: t('sys.api.successTip'), content: successMsg })
else if (options.successMessageMode === 'message') else if (options.successMessageMode === 'message')
createMessage.success(successMsg) createMessage.success(successMsg)
@ -98,6 +99,7 @@ const transform: AxiosTransform = {
// errorMessageMode='none' 一般是调用时明确表示不希望自动弹出错误提示 // errorMessageMode='none' 一般是调用时明确表示不希望自动弹出错误提示
if (options.errorMessageMode === 'modal') if (options.errorMessageMode === 'modal')
createErrorModal({ title: t('sys.api.errorTip'), content: timeoutMsg }) createErrorModal({ title: t('sys.api.errorTip'), content: timeoutMsg })
else if (options.errorMessageMode === 'message') else if (options.errorMessageMode === 'message')
createMessage.error(timeoutMsg) createMessage.error(timeoutMsg)
@ -150,7 +152,11 @@ const transform: AxiosTransform = {
else { else {
if (!isString(params)) { if (!isString(params)) {
formatDate && formatRequestDate(params) formatDate && formatRequestDate(params)
if (Reflect.has(config, 'data') && config.data && (Object.keys(config.data).length > 0 || config.data instanceof FormData)) { if (
Reflect.has(config, 'data')
&& config.data
&& (Object.keys(config.data).length > 0 || config.data instanceof FormData)
) {
config.data = data config.data = data
config.params = params config.params = params
} }
@ -159,8 +165,12 @@ const transform: AxiosTransform = {
config.data = params config.data = params
config.params = undefined config.params = undefined
} }
if (joinParamsToUrl) if (joinParamsToUrl) {
config.url = setObjToUrlParams(config.url as string, Object.assign({}, config.params, config.data)) config.url = setObjToUrlParams(
config.url as string,
Object.assign({}, config.params, config.data),
)
}
} }
else { else {
// 兼容restful风格 // 兼容restful风格
@ -188,7 +198,9 @@ const transform: AxiosTransform = {
const token = getAccessToken() const token = getAccessToken()
if (token && !isToken) { if (token && !isToken) {
// jwt token // jwt token
;(config as Recordable).headers.Authorization = options.authenticationScheme ? `${options.authenticationScheme} ${token}` : token (config as Recordable).headers.Authorization = options.authenticationScheme
? `${options.authenticationScheme} ${token}`
: token
} }
// 设置租户 // 设置租户
if (tenantEnable && tenantEnable === 'true') { if (tenantEnable && tenantEnable === 'true') {
@ -232,6 +244,7 @@ const transform: AxiosTransform = {
if (errMessage) { if (errMessage) {
if (errorMessageMode === 'modal') if (errorMessageMode === 'modal')
createErrorModal({ title: t('sys.api.errorTip'), content: errMessage }) createErrorModal({ title: t('sys.api.errorTip'), content: errMessage })
else if (errorMessageMode === 'message') else if (errorMessageMode === 'message')
createMessage.error(errMessage) createMessage.error(errMessage)
@ -239,7 +252,7 @@ const transform: AxiosTransform = {
} }
} }
catch (error) { catch (error) {
throw new Error(error as string) throw new Error(error as unknown as string)
} }
checkStatus(error?.response?.status, msg, errorMessageMode) checkStatus(error?.response?.status, msg, errorMessageMode)
@ -250,7 +263,6 @@ const transform: AxiosTransform = {
config.method?.toUpperCase() === RequestEnum.GET config.method?.toUpperCase() === RequestEnum.GET
&& isOpenRetry && isOpenRetry
&& retryRequest.retry(axiosInstance, error) && retryRequest.retry(axiosInstance, error)
return Promise.reject(error) return Promise.reject(error)
}, },
} }