|
@@ -0,0 +1,79 @@
|
|
|
+import axios, { AxiosRequestConfig, Canceler } from 'axios'
|
|
|
+
|
|
|
+const Toast = (message: string) => {}
|
|
|
+Toast.loading = () => {}
|
|
|
+Toast.hide = () => {}
|
|
|
+
|
|
|
+export const netErrMsg = '系统开小差了,请稍候再试'
|
|
|
+
|
|
|
+interface RequestConfig extends AxiosRequestConfig {
|
|
|
+ contentType?: 'json' | 'form'
|
|
|
+ reportError?: boolean
|
|
|
+ showLoading?: boolean
|
|
|
+ cancelable?: boolean
|
|
|
+}
|
|
|
+
|
|
|
+interface ResponseData<T = any> {
|
|
|
+ success: boolean
|
|
|
+ results: T
|
|
|
+ message: string
|
|
|
+}
|
|
|
+
|
|
|
+const _axios = axios.create({
|
|
|
+ baseURL: import.meta.env.VITE_API_BASE,
|
|
|
+})
|
|
|
+const cancelMethods: Record<string, Canceler> = {}
|
|
|
+
|
|
|
+_axios.interceptors.request.use((config: RequestConfig) => {
|
|
|
+ config.showLoading && Toast.loading()
|
|
|
+ cancelMethods[config.url!]?.()
|
|
|
+ delete cancelMethods[config.url!]
|
|
|
+ if (config.cancelable) {
|
|
|
+ config.cancelToken = new axios.CancelToken(
|
|
|
+ c => (cancelMethods[config.url!] = c)
|
|
|
+ )
|
|
|
+ }
|
|
|
+ if (
|
|
|
+ config.method === 'post' &&
|
|
|
+ config.contentType !== 'json' &&
|
|
|
+ Object.prototype.toString.call(config.data) === '[object Object]'
|
|
|
+ ) {
|
|
|
+ config.data = new URLSearchParams(config.data)
|
|
|
+ }
|
|
|
+
|
|
|
+ return config
|
|
|
+})
|
|
|
+
|
|
|
+_axios.interceptors.response.use(
|
|
|
+ response => {
|
|
|
+ const config = response.config as RequestConfig
|
|
|
+ config.showLoading && Toast.hide()
|
|
|
+ const data = response.data as ResponseData | Blob | undefined
|
|
|
+ if (!data || data instanceof Blob || data.success) return data
|
|
|
+ config.reportError && Toast(data.message || netErrMsg)
|
|
|
+ return Promise.reject(data)
|
|
|
+ },
|
|
|
+ error => {
|
|
|
+ Toast.hide()
|
|
|
+ if (!axios.isCancel(error) && error.config?.reportError) {
|
|
|
+ Toast(netErrMsg)
|
|
|
+ }
|
|
|
+ return Promise.reject(error)
|
|
|
+ }
|
|
|
+)
|
|
|
+
|
|
|
+export default function request<T = any>(
|
|
|
+ config: RequestConfig
|
|
|
+): Promise<ResponseData<T>> {
|
|
|
+ config.transformRequest = ([] as any[]).concat(
|
|
|
+ config.transformRequest || [],
|
|
|
+ axios.defaults.transformRequest
|
|
|
+ )
|
|
|
+ return _axios(config) as any
|
|
|
+}
|
|
|
+
|
|
|
+request.get = <T = any>(url: string, config?: RequestConfig) =>
|
|
|
+ request<T>({ ...config, url })
|
|
|
+
|
|
|
+request.post = <T = any>(url: string, data?: any, config?: RequestConfig) =>
|
|
|
+ request<T>({ ...config, method: 'POST', url, data })
|