|
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';
|
sanmu
authored
|
16
17
18
|
import { useMessage } from '/@/hooks/web/useMessage';
import { router } from '/@/router';
import { useUserStoreWithOut } from '/@/store/modules/user';
|
|
19
20
|
export * from './axiosTransform';
|
sanmu
authored
|
21
|
const { createMessage } = useMessage();
|
|
22
23
|
/**
|
vben
authored
|
24
|
* @description: axios module
|
|
25
26
27
|
*/
export class VAxios {
private axiosInstance: AxiosInstance;
|
vben
authored
|
28
|
private readonly options: CreateAxiosOptions;
|
|
29
30
31
32
33
34
35
36
|
constructor(options: CreateAxiosOptions) {
this.options = options;
this.axiosInstance = axios.create(options);
this.setupInterceptors();
}
/**
|
vben
authored
|
37
|
* @description: Create axios instance
|
|
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;
}
/**
|
vben
authored
|
53
|
* @description: Reconfigure axios
|
|
54
55
56
57
58
59
60
61
62
|
*/
configAxios(config: CreateAxiosOptions) {
if (!this.axiosInstance) {
return;
}
this.createAxios(config);
}
/**
|
vben
authored
|
63
|
* @description: Set general header
|
|
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 拦截器配置
|
|
74
75
|
*/
private setupInterceptors() {
|
|
76
77
78
79
80
|
// const transform = this.getTransform();
const {
axiosInstance,
options: { transform },
} = this;
|
|
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();
|
vben
authored
|
93
|
// Request interceptor configuration processing
|
|
94
|
this.axiosInstance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
|
vben
authored
|
95
|
// If cancel repeat request is turned on, then cancel repeat request is prohibited
|
|
96
97
98
99
100
|
const { requestOptions } = this.options;
const ignoreCancelToken = requestOptions?.ignoreCancelToken ?? true;
!ignoreCancelToken && axiosCanceler.addPending(config);
|
|
101
|
if (requestInterceptors && isFunction(requestInterceptors)) {
|
Vben
authored
|
102
|
config = requestInterceptors(config, this.options);
|
|
103
104
105
106
|
}
return config;
}, undefined);
|
vben
authored
|
107
|
// Request interceptor error capture
|
|
108
109
110
111
|
requestInterceptorsCatch &&
isFunction(requestInterceptorsCatch) &&
this.axiosInstance.interceptors.request.use(undefined, requestInterceptorsCatch);
|
vben
authored
|
112
|
// Response result interceptor processing
|
|
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);
|
vben
authored
|
121
|
// Response result interceptor error capture
|
|
122
123
|
responseInterceptorsCatch &&
isFunction(responseInterceptorsCatch) &&
|
|
124
|
this.axiosInstance.interceptors.response.use(undefined, (error) => {
|
|
125
|
return responseInterceptorsCatch(axiosInstance, error);
|
|
126
|
});
|
|
127
128
|
}
|
|
129
|
/**
|
vben
authored
|
130
|
* @description: File Upload
|
|
131
132
133
|
*/
uploadFile<T = any>(config: AxiosRequestConfig, params: UploadFileParams) {
const formData = new window.FormData();
|
erniu
authored
|
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);
}
|
|
141
142
143
|
if (params.data) {
Object.keys(params.data).forEach((key) => {
|
erniu
authored
|
144
|
const value = params.data![key];
|
|
145
146
147
148
149
150
151
|
if (Array.isArray(value)) {
value.forEach((item) => {
formData.append(`${key}[]`, item);
});
return;
}
|
erniu
authored
|
152
|
formData.append(key, params.data![key]);
|
|
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
|
|
163
164
165
166
|
ignoreCancelToken: true,
},
});
}
|
|
167
|
|
Vben
authored
|
168
169
|
// support form-data
supportFormData(config: AxiosRequestConfig) {
|
|
170
|
const headers = config.headers || this.options.headers;
|
Vben
authored
|
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,
|
|
183
|
data: qs.stringify(config.data, { arrayFormat: 'brackets' }),
|
Vben
authored
|
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);
}
|
|
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
|
|
|
210
211
212
|
const transform = this.getTransform();
const { requestOptions } = this.options;
|
sanmu
authored
|
213
|
const { message } = options || {};
|
|
214
215
216
|
const opt: RequestOptions = Object.assign({}, requestOptions, options);
|
|
217
|
const { beforeRequestHook, requestCatchHook, transformResponseHook } = transform || {};
|
|
218
219
220
|
if (beforeRequestHook && isFunction(beforeRequestHook)) {
conf = beforeRequestHook(conf, opt);
}
|
|
221
|
conf.requestOptions = opt;
|
Vben
authored
|
222
223
|
conf = this.supportFormData(conf);
|
Vben
authored
|
224
|
|
|
225
|
return new Promise((resolve, reject) => {
|
sanmu
authored
|
226
227
|
const userStore = useUserStoreWithOut();
|
|
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!'));
}
|
|
251
252
|
return;
}
|
|
253
|
resolve(res as unknown as Promise<T>);
|
|
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));
|
|
259
260
|
return;
}
|
|
261
262
263
|
if (axios.isAxiosError(e)) {
// rewrite error message from axios in here
}
|
|
264
265
266
267
268
|
reject(e);
});
});
}
}
|