Blame view

src/utils/http/axios/Axios.ts 7.84 KB
Kirk Lin authored
1
2
3
4
5
6
7
import type {
  AxiosRequestConfig,
  AxiosInstance,
  AxiosResponse,
  AxiosError,
  InternalAxiosRequestConfig,
} from 'axios';
8
import type { RequestOptions, Result, UploadFileParams } from '/#/axios';
Vben authored
9
import type { CreateAxiosOptions } from './axiosTransform';
陈文彬 authored
10
import axios from 'axios';
Vben authored
11
import qs from 'qs';
陈文彬 authored
12
13
import { AxiosCanceler } from './axiosCancel';
import { isFunction } from '/@/utils/is';
14
import { cloneDeep } from 'lodash-es';
15
import { ContentTypeEnum, RequestEnum } from '/@/enums/httpEnum';
sanmu authored
16
17
18
import { useMessage } from '/@/hooks/web/useMessage';
import { router } from '/@/router';
import { useUserStoreWithOut } from '/@/store/modules/user';
陈文彬 authored
19
20

export * from './axiosTransform';
sanmu authored
21
const { createMessage } = useMessage();
陈文彬 authored
22
23

/**
24
 * @description:  axios module
陈文彬 authored
25
26
27
 */
export class VAxios {
  private axiosInstance: AxiosInstance;
vben authored
28
  private readonly options: CreateAxiosOptions;
陈文彬 authored
29
30
31
32
33
34
35
36

  constructor(options: CreateAxiosOptions) {
    this.options = options;
    this.axiosInstance = axios.create(options);
    this.setupInterceptors();
  }

  /**
37
   * @description:  Create axios instance
陈文彬 authored
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
   */
  private createAxios(config: CreateAxiosOptions): void {
    this.axiosInstance = axios.create(config);
  }

  private getTransform() {
    const { transform } = this.options;
    return transform;
  }

  getAxios(): AxiosInstance {
    return this.axiosInstance;
  }

  /**
53
   * @description: Reconfigure axios
陈文彬 authored
54
55
56
57
58
59
60
61
62
   */
  configAxios(config: CreateAxiosOptions) {
    if (!this.axiosInstance) {
      return;
    }
    this.createAxios(config);
  }

  /**
63
   * @description: Set general header
陈文彬 authored
64
65
66
67
68
69
70
71
72
   */
  setHeader(headers: any): void {
    if (!this.axiosInstance) {
      return;
    }
    Object.assign(this.axiosInstance.defaults.headers, headers);
  }

  /**
73
   * @description: Interceptor configuration 拦截器配置
陈文彬 authored
74
75
   */
  private setupInterceptors() {
Kirk Lin authored
76
77
78
79
80
    // const transform = this.getTransform();
    const {
      axiosInstance,
      options: { transform },
    } = this;
陈文彬 authored
81
82
83
84
85
86
87
88
89
90
91
92
    if (!transform) {
      return;
    }
    const {
      requestInterceptors,
      requestInterceptorsCatch,
      responseInterceptors,
      responseInterceptorsCatch,
    } = transform;

    const axiosCanceler = new AxiosCanceler();
93
    // Request interceptor configuration processing
Kirk Lin authored
94
    this.axiosInstance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
95
      // If cancel repeat request is turned on, then cancel repeat request is prohibited
Kirk Lin authored
96
97
98
99
100
      const { requestOptions } = this.options;
      const ignoreCancelToken = requestOptions?.ignoreCancelToken ?? true;

      !ignoreCancelToken && axiosCanceler.addPending(config);
陈文彬 authored
101
      if (requestInterceptors && isFunction(requestInterceptors)) {
102
        config = requestInterceptors(config, this.options);
陈文彬 authored
103
104
105
106
      }
      return config;
    }, undefined);
107
    // Request interceptor error capture
陈文彬 authored
108
109
110
111
    requestInterceptorsCatch &&
      isFunction(requestInterceptorsCatch) &&
      this.axiosInstance.interceptors.request.use(undefined, requestInterceptorsCatch);
112
    // Response result interceptor processing
陈文彬 authored
113
114
115
116
117
118
119
120
    this.axiosInstance.interceptors.response.use((res: AxiosResponse<any>) => {
      res && axiosCanceler.removePending(res.config);
      if (responseInterceptors && isFunction(responseInterceptors)) {
        res = responseInterceptors(res);
      }
      return res;
    }, undefined);
121
    // Response result interceptor error capture
陈文彬 authored
122
123
    responseInterceptorsCatch &&
      isFunction(responseInterceptorsCatch) &&
124
      this.axiosInstance.interceptors.response.use(undefined, (error) => {
Kirk Lin authored
125
        return responseInterceptorsCatch(axiosInstance, error);
126
      });
陈文彬 authored
127
128
  }
jq authored
129
  /**
130
   * @description:  File Upload
jq authored
131
132
133
   */
  uploadFile<T = any>(config: AxiosRequestConfig, params: UploadFileParams) {
    const formData = new window.FormData();
134
135
136
137
138
139
140
    const customFilename = params.name || 'file';

    if (params.filename) {
      formData.append(customFilename, params.file, params.filename);
    } else {
      formData.append(customFilename, params.file);
    }
jq authored
141
142
143

    if (params.data) {
      Object.keys(params.data).forEach((key) => {
144
        const value = params.data![key];
jq authored
145
146
147
148
149
150
151
        if (Array.isArray(value)) {
          value.forEach((item) => {
            formData.append(`${key}[]`, item);
          });
          return;
        }
152
        formData.append(key, params.data![key]);
jq authored
153
154
155
156
157
158
159
160
161
      });
    }

    return this.axiosInstance.request<T>({
      ...config,
      method: 'POST',
      data: formData,
      headers: {
        'Content-type': ContentTypeEnum.FORM_DATA,
vben authored
162
        // @ts-ignore
jq authored
163
164
165
166
        ignoreCancelToken: true,
      },
    });
  }
陈文彬 authored
167
168
169
  // support form-data
  supportFormData(config: AxiosRequestConfig) {
170
    const headers = config.headers || this.options.headers;
171
172
173
174
175
176
177
178
179
180
181
182
    const contentType = headers?.['Content-Type'] || headers?.['content-type'];

    if (
      contentType !== ContentTypeEnum.FORM_URLENCODED ||
      !Reflect.has(config, 'data') ||
      config.method?.toUpperCase() === RequestEnum.GET
    ) {
      return config;
    }

    return {
      ...config,
最后 authored
183
      data: qs.stringify(config.data, { arrayFormat: 'brackets' }),
184
185
186
    };
  }
Vben authored
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
  get<T = any>(config: AxiosRequestConfig, options?: RequestOptions): Promise<T> {
    return this.request({ ...config, method: 'GET' }, options);
  }

  post<T = any>(config: AxiosRequestConfig, options?: RequestOptions): Promise<T> {
    return this.request({ ...config, method: 'POST' }, options);
  }

  put<T = any>(config: AxiosRequestConfig, options?: RequestOptions): Promise<T> {
    return this.request({ ...config, method: 'PUT' }, options);
  }

  delete<T = any>(config: AxiosRequestConfig, options?: RequestOptions): Promise<T> {
    return this.request({ ...config, method: 'DELETE' }, options);
  }
陈文彬 authored
203
  request<T = any>(config: AxiosRequestConfig, options?: RequestOptions): Promise<T> {
204
    let conf: CreateAxiosOptions = cloneDeep(config);
205
    // cancelToken 如果被深拷贝,会导致最外层无法使用cancel方法来取消请求
vben authored
206
207
    if (config.cancelToken) {
      conf.cancelToken = config.cancelToken;
208
    }
vben authored
209
陈文彬 authored
210
211
212
    const transform = this.getTransform();

    const { requestOptions } = this.options;
sanmu authored
213
    const { message } = options || {};
陈文彬 authored
214
215
216

    const opt: RequestOptions = Object.assign({}, requestOptions, options);
217
    const { beforeRequestHook, requestCatchHook, transformResponseHook } = transform || {};
陈文彬 authored
218
219
220
    if (beforeRequestHook && isFunction(beforeRequestHook)) {
      conf = beforeRequestHook(conf, opt);
    }
221
    conf.requestOptions = opt;
222
223

    conf = this.supportFormData(conf);
224
陈文彬 authored
225
    return new Promise((resolve, reject) => {
sanmu authored
226
227
      const userStore = useUserStoreWithOut();
陈文彬 authored
228
229
230
      this.axiosInstance
        .request<any, AxiosResponse<Result>>(conf)
        .then((res: AxiosResponse<Result>) => {
sanmu authored
231
232
233
234
235
236
          if (res.data.result === 401) {
            userStore.setToken('');
            createMessage.error(res.data.message);
            return router.push('/login');
          }
          if (res.data.result !== 0 && res.data.message) {
sanmu authored
237
238
            createMessage.error(res.data.message);
            return reject(res.data);
sanmu authored
239
240
241
242
243
          }

          if (message && res.data.result === 0) {
            createMessage.success(message);
          }
244
          if (transformResponseHook && isFunction(transformResponseHook)) {
245
            try {
246
              const ret = transformResponseHook(res, opt);
247
248
249
250
              resolve(ret);
            } catch (err) {
              reject(err || new Error('request error!'));
            }
陈文彬 authored
251
252
            return;
          }
253
          resolve(res as unknown as Promise<T>);
陈文彬 authored
254
        })
255
        .catch((e: Error | AxiosError) => {
sanmu authored
256
          console.log('%c [ e ]-257', 'font-size:13px; background:pink; color:#bf2c9f;', e);
Vben authored
257
          if (requestCatchHook && isFunction(requestCatchHook)) {
258
            reject(requestCatchHook(e, opt));
陈文彬 authored
259
260
            return;
          }
261
262
263
          if (axios.isAxiosError(e)) {
            // rewrite error message from axios in here
          }
陈文彬 authored
264
265
266
267
268
          reject(e);
        });
    });
  }
}