|
|
@@ -2,6 +2,7 @@ import axios, { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse, In
|
|
|
import { useUserStore } from '@/store/modules/user'
|
|
|
import { $t } from '@/locales'
|
|
|
import { ApiResponse, ApiResponsePage, ApiStatus } from './server.type'
|
|
|
+import { createHttpError, handleUnauthorizedError, showError } from './server.help'
|
|
|
|
|
|
/** 扩展 AxiosRequestConfig */
|
|
|
interface ExtendedAxiosRequestConfig extends AxiosRequestConfig {
|
|
|
@@ -31,7 +32,7 @@ export class RequestHttp {
|
|
|
return request
|
|
|
},
|
|
|
(error: AxiosError) => {
|
|
|
- // showError(createHttpError($t('httpMsg.requestConfigError'), ApiStatus.error))
|
|
|
+ showError(createHttpError($t('httpMsg.requestConfigError'), ApiStatus.error), config.showErrorMessage ?? true)
|
|
|
return Promise.reject(error)
|
|
|
}
|
|
|
)
|
|
|
@@ -43,21 +44,21 @@ export class RequestHttp {
|
|
|
(response: AxiosResponse<Http.BaseResponse>) => {
|
|
|
const { code, msg } = response.data
|
|
|
if (code === ApiStatus.success) return response
|
|
|
- if (code === ApiStatus.unauthorized) {
|
|
|
- setTimeout(() => useUserStore().logOut(), 500)
|
|
|
- }
|
|
|
+ if (code === ApiStatus.unauthorized) handleUnauthorizedError(msg)
|
|
|
throw new Error(msg || $t('httpMsg.requestFailed'))
|
|
|
},
|
|
|
(error) => {
|
|
|
- if (error.response?.status === ApiStatus.unauthorized) {
|
|
|
- setTimeout(() => useUserStore().logOut(), 500)
|
|
|
- }
|
|
|
+ if (error.response?.status === ApiStatus.unauthorized) handleUnauthorizedError()
|
|
|
return Promise.reject(error)
|
|
|
}
|
|
|
)
|
|
|
}
|
|
|
|
|
|
public request<T = any>(config: ExtendedAxiosRequestConfig): Promise<T> {
|
|
|
+ if (['POST', 'PUT'].includes(config.method?.toUpperCase() || '') && config.params && !config.data) {
|
|
|
+ config.data = config.params
|
|
|
+ config.params = undefined
|
|
|
+ }
|
|
|
return this.service.request(config)
|
|
|
}
|
|
|
/**
|
|
|
@@ -86,4 +87,22 @@ export class RequestHttp {
|
|
|
public download(url: string, params?: object, _object: ExtendedAxiosRequestConfig = {}): Promise<BlobPart> {
|
|
|
return this.service.post(url, params, { ..._object, responseType: 'blob' })
|
|
|
}
|
|
|
+
|
|
|
+ public upload(url: string, data: Record<string, any> & { file: Blob | File }, _object: ExtendedAxiosRequestConfig = {}): Promise<ApiResponse> {
|
|
|
+ const formData = new FormData()
|
|
|
+ Object.entries(data).forEach(([key, value]) => {
|
|
|
+ if (Array.isArray(value)) {
|
|
|
+ value.forEach((item, index) => {
|
|
|
+ formData.append(`${key}[${index}]`, item)
|
|
|
+ })
|
|
|
+ } else {
|
|
|
+ formData.append(key, value)
|
|
|
+ }
|
|
|
+ })
|
|
|
+ const finalConfig: ExtendedAxiosRequestConfig = {
|
|
|
+ ..._object,
|
|
|
+ headers: { 'Content-Type': 'multipart/form-data', ..._object?.headers }
|
|
|
+ }
|
|
|
+ return this.service.post(url, formData, finalConfig)
|
|
|
+ }
|
|
|
}
|