Blame view

src/utils/http/axios/Axios.ts 7.04 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';
陈文彬 authored
16
17
18
19

export * from './axiosTransform';

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

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

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

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

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

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

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

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

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

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

    if (params.filename) {
      formData.append(customFilename, params.file, params.filename);
    } else {
      formData.append(customFilename, params.file);
    }
jq authored
137
138
139

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

    return this.axiosInstance.request<T>({
      ...config,
      method: 'POST',
      data: formData,
      headers: {
        'Content-type': ContentTypeEnum.FORM_DATA,
vben authored
158
        // @ts-ignore
jq authored
159
160
161
162
        ignoreCancelToken: true,
      },
    });
  }
陈文彬 authored
163
164
165
  // support form-data
  supportFormData(config: AxiosRequestConfig) {
166
    const headers = config.headers || this.options.headers;
167
168
169
170
171
172
173
174
175
176
177
178
    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
179
      data: qs.stringify(config.data, { arrayFormat: 'brackets' }),
180
181
182
    };
  }
Vben authored
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
  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
199
  request<T = any>(config: AxiosRequestConfig, options?: RequestOptions): Promise<T> {
200
    let conf: CreateAxiosOptions = cloneDeep(config);
201
    // cancelToken 如果被深拷贝,会导致最外层无法使用cancel方法来取消请求
vben authored
202
203
    if (config.cancelToken) {
      conf.cancelToken = config.cancelToken;
204
    }
vben authored
205
陈文彬 authored
206
207
208
209
210
211
    const transform = this.getTransform();

    const { requestOptions } = this.options;

    const opt: RequestOptions = Object.assign({}, requestOptions, options);
212
    const { beforeRequestHook, requestCatchHook, transformResponseHook } = transform || {};
陈文彬 authored
213
214
215
    if (beforeRequestHook && isFunction(beforeRequestHook)) {
      conf = beforeRequestHook(conf, opt);
    }
216
    conf.requestOptions = opt;
217
218

    conf = this.supportFormData(conf);
219
陈文彬 authored
220
221
222
223
    return new Promise((resolve, reject) => {
      this.axiosInstance
        .request<any, AxiosResponse<Result>>(conf)
        .then((res: AxiosResponse<Result>) => {
224
          if (transformResponseHook && isFunction(transformResponseHook)) {
225
            try {
226
              const ret = transformResponseHook(res, opt);
227
228
229
230
              resolve(ret);
            } catch (err) {
              reject(err || new Error('request error!'));
            }
陈文彬 authored
231
232
            return;
          }
233
          resolve(res as unknown as Promise<T>);
陈文彬 authored
234
        })
235
        .catch((e: Error | AxiosError) => {
Vben authored
236
          if (requestCatchHook && isFunction(requestCatchHook)) {
237
            reject(requestCatchHook(e, opt));
陈文彬 authored
238
239
            return;
          }
240
241
242
          if (axios.isAxiosError(e)) {
            // rewrite error message from axios in here
          }
陈文彬 authored
243
244
245
246
247
          reject(e);
        });
    });
  }
}