|
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';
|
|
10
|
import axios from 'axios';
|
Vben
authored
|
11
|
import qs from 'qs';
|
|
12
13
|
import { AxiosCanceler } from './axiosCancel';
import { isFunction } from '/@/utils/is';
|
erniu
authored
|
14
|
import { cloneDeep } from 'lodash-es';
|
vben
authored
|
15
|
import { ContentTypeEnum, RequestEnum } from '/@/enums/httpEnum';
|
|
16
17
18
19
|
export * from './axiosTransform';
/**
|
vben
authored
|
20
|
* @description: axios module
|
|
21
22
23
|
*/
export class VAxios {
private axiosInstance: AxiosInstance;
|
vben
authored
|
24
|
private readonly options: CreateAxiosOptions;
|
|
25
26
27
28
29
30
31
32
|
constructor(options: CreateAxiosOptions) {
this.options = options;
this.axiosInstance = axios.create(options);
this.setupInterceptors();
}
/**
|
vben
authored
|
33
|
* @description: Create axios instance
|
|
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;
}
/**
|
vben
authored
|
49
|
* @description: Reconfigure axios
|
|
50
51
52
53
54
55
56
57
58
|
*/
configAxios(config: CreateAxiosOptions) {
if (!this.axiosInstance) {
return;
}
this.createAxios(config);
}
/**
|
vben
authored
|
59
|
* @description: Set general header
|
|
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 拦截器配置
|
|
70
71
|
*/
private setupInterceptors() {
|
|
72
73
74
75
76
|
// const transform = this.getTransform();
const {
axiosInstance,
options: { transform },
} = this;
|
|
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();
|
vben
authored
|
89
|
// Request interceptor configuration processing
|
|
90
|
this.axiosInstance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
|
vben
authored
|
91
|
// If cancel repeat request is turned on, then cancel repeat request is prohibited
|
|
92
93
94
95
96
|
const { requestOptions } = this.options;
const ignoreCancelToken = requestOptions?.ignoreCancelToken ?? true;
!ignoreCancelToken && axiosCanceler.addPending(config);
|
|
97
|
if (requestInterceptors && isFunction(requestInterceptors)) {
|
Vben
authored
|
98
|
config = requestInterceptors(config, this.options);
|
|
99
100
101
102
|
}
return config;
}, undefined);
|
vben
authored
|
103
|
// Request interceptor error capture
|
|
104
105
106
107
|
requestInterceptorsCatch &&
isFunction(requestInterceptorsCatch) &&
this.axiosInstance.interceptors.request.use(undefined, requestInterceptorsCatch);
|
vben
authored
|
108
|
// Response result interceptor processing
|
|
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);
|
vben
authored
|
117
|
// Response result interceptor error capture
|
|
118
119
|
responseInterceptorsCatch &&
isFunction(responseInterceptorsCatch) &&
|
|
120
|
this.axiosInstance.interceptors.response.use(undefined, (error) => {
|
|
121
|
return responseInterceptorsCatch(axiosInstance, error);
|
|
122
|
});
|
|
123
124
|
}
|
|
125
|
/**
|
vben
authored
|
126
|
* @description: File Upload
|
|
127
128
129
|
*/
uploadFile<T = any>(config: AxiosRequestConfig, params: UploadFileParams) {
const formData = new window.FormData();
|
erniu
authored
|
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);
}
|
|
137
138
139
|
if (params.data) {
Object.keys(params.data).forEach((key) => {
|
erniu
authored
|
140
|
const value = params.data![key];
|
|
141
142
143
144
145
146
147
|
if (Array.isArray(value)) {
value.forEach((item) => {
formData.append(`${key}[]`, item);
});
return;
}
|
erniu
authored
|
148
|
formData.append(key, params.data![key]);
|
|
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
|
|
159
160
161
162
|
ignoreCancelToken: true,
},
});
}
|
|
163
|
|
Vben
authored
|
164
165
|
// support form-data
supportFormData(config: AxiosRequestConfig) {
|
|
166
|
const headers = config.headers || this.options.headers;
|
Vben
authored
|
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,
|
|
179
|
data: qs.stringify(config.data, { arrayFormat: 'brackets' }),
|
Vben
authored
|
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);
}
|
|
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
|
|
|
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 || {};
|
|
213
214
215
|
if (beforeRequestHook && isFunction(beforeRequestHook)) {
conf = beforeRequestHook(conf, opt);
}
|
|
216
|
conf.requestOptions = opt;
|
Vben
authored
|
217
218
|
conf = this.supportFormData(conf);
|
Vben
authored
|
219
|
|
|
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!'));
}
|
|
231
232
|
return;
}
|
|
233
|
resolve(res as unknown as Promise<T>);
|
|
234
|
})
|
|
235
|
.catch((e: Error | AxiosError) => {
|
Vben
authored
|
236
|
if (requestCatchHook && isFunction(requestCatchHook)) {
|
|
237
|
reject(requestCatchHook(e, opt));
|
|
238
239
|
return;
}
|
|
240
241
242
|
if (axios.isAxiosError(e)) {
// rewrite error message from axios in here
}
|
|
243
244
245
246
247
|
reject(e);
});
});
}
}
|