发布于 

TypeScript基于Axios的二次封装

为了更好的贴近应用,享受完美的TS类型提示,基于原生Axios进行二次封装。

目录结构

utils下新建http文件夹,其中包含三个文件,http-service.ts、index.ts、interceptors.ts

types文件下新建axios.d.ts

代码组成

http-service.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import axios from 'axios';
import qs from 'qs';

import type {
AxiosRequestConfig,
AxiosResponse,
AxiosInstance,
AxiosError,
} from 'axios';
import type { CreateAxiosOptions } from './interceptors';
import type { RequestOptions, Result, UploadFileParams } from '@/types/axios';

import { isFunction } from '../is';
import { cloneDeep } from 'lodash-es';

export class HttpService {
private axiosInstance: AxiosInstance;
private readonly options: CreateAxiosOptions;

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

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

/**
* @description: 请求头参数入参
*/
setHeader(headers: any): void {
if (!this.axiosInstance) {
return;
}
Object.assign(this.axiosInstance.defaults.headers, headers);
}

/**
* @description: Interceptor configuration 拦截器配置
*/
private setupInterceptors() {
const transform = this.getTransform();
if (!transform) {
return;
}
const {
requestInterceptors,
requestInterceptorsCatch,
responseInterceptors,
responseInterceptorsCatch,
} = transform;

// request 拦截器
this.axiosInstance.interceptors.request.use(
(config: AxiosRequestConfig) => {
if (requestInterceptors && isFunction(requestInterceptors)) {
config = requestInterceptors(config, this.options);
}
return config;
}
);

// request 异常捕获
requestInterceptorsCatch &&
isFunction(requestInterceptorsCatch) &&
this.axiosInstance.interceptors.request.use(
undefined,
requestInterceptorsCatch
);

// response 拦截器
this.axiosInstance.interceptors.response.use(
(response: AxiosResponse<any>) => {
if (responseInterceptors && isFunction(responseInterceptors)) {
response = responseInterceptors(response);
}
return response;
}
);

// response 异常捕获
responseInterceptorsCatch &&
isFunction(responseInterceptorsCatch) &&
this.axiosInstance.interceptors.response.use(undefined, (error) => {
// @ts-ignore
return responseInterceptorsCatch(this.axiosInstance, error);
});
}

/**
* @description: 文件上传
*/
uploadFile<T = any>(config: AxiosRequestConfig, params: UploadFileParams) {
const formData = new window.FormData();
const customFilename = params.name || 'file';

if (params.filename) {
formData.append(customFilename, params.file, params.filename);
} else {
formData.append(customFilename, params.file);
}

if (params.data) {
Object.keys(params.data).forEach((key) => {
const value = params.data![key];
if (Array.isArray(value)) {
value.forEach((item) => {
formData.append(`${key}[]`, item);
});
return;
}

formData.append(key, params.data![key]);
});
}

return this.axiosInstance.request<T>({
...config,
method: 'POST',
data: formData,
headers: {
'Content-type': 'multipart/form-data;charset=UTF-8',
},
});
}

// 支持 form-data
supportFormData(config: AxiosRequestConfig) {
const headers = config.headers || this.options.headers;
// @ts-ignore
const contentType = headers?.['Content-Type'] || headers?.['content-type'];

if (
contentType !== 'application/x-www-form-urlencoded;charset=UTF-8' ||
!Reflect.has(config, 'data') ||
config.method?.toUpperCase() === 'GET'
) {
return config;
}

return {
...config,
data: qs.stringify(config.data, { arrayFormat: 'brackets' }),
};
}

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

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

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

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

request<U = any, T = Result<U>>(
config: AxiosRequestConfig,
options?: RequestOptions
): Promise<T> {
let conf: CreateAxiosOptions = cloneDeep(config);
const transform = this.getTransform();

const { requestOptions } = this.options;

const opt: RequestOptions = Object.assign({}, requestOptions, options);

const { beforeRequestHook, requestCatchHook, transformResponseHook } =
transform || {};
if (beforeRequestHook && isFunction(beforeRequestHook)) {
conf = beforeRequestHook(conf, opt);
}
conf.requestOptions = opt;

conf = this.supportFormData(conf);

return new Promise((resolve, reject) => {
this.axiosInstance
.request<any, AxiosResponse<Result>>(conf)
.then((res: AxiosResponse<Result>) => {
if (transformResponseHook && isFunction(transformResponseHook)) {
try {
const ret = transformResponseHook(res, opt);
resolve(ret);
} catch (err) {
reject(err || new Error('request error!'));
}
return;
}
resolve(res as unknown as Promise<T>);
})
.catch((e: Error | AxiosError) => {
if (requestCatchHook && isFunction(requestCatchHook)) {
reject(requestCatchHook(e, opt));
return;
}
reject(e);
});
});
}
}

index.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
import type { AxiosResponse } from 'axios';
import type { AxiosTransform, CreateAxiosOptions } from './interceptors';
import type { RequestOptions, Result } from '@/types/axios';

import { showNotify } from 'vant';
import { clone } from 'lodash-es';
import { HttpService } from './http-service';
import { useUserStore } from '@/store';
import { getToken, getAesStr } from '@/utils/auth';
import { isString, isObject } from '@/utils/is';
import { setObjToUrlParams, deepMerge } from '@/utils';

declare type Recordable<T = any> = Record<string, T>;

/**
* @description: 格式化请求时间
*/
const formatRequestDate = (params: Recordable) => {
if (Object.prototype.toString.call(params) !== '[object Object]') {
return;
}

for (const key in params) {
const format = params[key]?.format ?? null;
if (format && typeof format === 'function') {
params[key] = params[key].format('YYYY-MM-DD HH:mm:ss');
}
if (isString(key)) {
const value = params[key];
if (value) {
try {
params[key] = isString(value) ? value.trim() : value;
} catch (error: any) {
throw new Error(error);
}
}
}
if (isObject(params[key])) {
formatRequestDate(params[key]);
}
}
};

interface JoinTimestampOptions<T extends boolean> {
(join: boolean, restful: T): T extends true ? string : object;
}

// 加时间戳参数
const joinTimestamp: JoinTimestampOptions<true | false> = (
join: boolean,
restful = false
) => {
if (!join) {
return restful ? '' : {};
}
const now = new Date().getTime();
if (restful) {
return `?_t=${now}`;
}
return { _t: now };
};

/**
* @description: 数据处理
*/
const transform: AxiosTransform = {
/**
* @description: 处理响应数据。如果数据不是预期格式,可直接抛出错误
*/
transformResponseHook: async (
res: AxiosResponse<Result>,
options: RequestOptions
) => {
const { isTransformResponse, isReturnNativeResponse } = options;

// 是否返回原生响应头 比如:需要获取响应头时使用该属性
if (isReturnNativeResponse) {
return res;
}

// 不进行任何处理,直接返回
if (!isTransformResponse) {
return res.data;
}

// 抛出异常
const { data } = res;
if (!data) {
throw new Error('请求出错,请稍候重试');
}

// 接口数据处理
const { code, msg } = data;
if (code === 0) {
return data;
} else {
showNotify({
message: msg || 'Error',
type: 'danger',
});
switch (code) {
case 403:
const userStore = useUserStore();
await userStore.logout();
window.location.reload();
break;

default:
break;
}
return Promise.reject(new Error(msg || 'Error'));
}
},
beforeRequestHook: (config, options) => {
const {
apiUrl,
joinPrefix,
joinParamsToUrl,
formatDate,
joinTime = true,
urlPrefix,
} = options;

// 合并前缀
if (joinPrefix) {
config.url = `${urlPrefix}${config.url}`;
}

// 接口地址,用于特殊处理url,不传则使用默认url
if (apiUrl && isString(apiUrl)) {
config.url = `${apiUrl}${config.url}`;
}

const params = config.params || {};
const data = config.data || false;

// 格式化请求参数时间
formatDate && data && !isString(data) && formatRequestDate(data);

if (config.method?.toUpperCase() === 'GET') {
if (!isString(params)) {
// 给 get 请求加上时间戳参数,避免从缓存中拿数据。
config.params = Object.assign(
params || {},
joinTimestamp(joinTime, false)
);
} else {
// 兼容restful风格
config.url = config.url + params + `${joinTimestamp(joinTime, true)}`;
config.params = undefined;
}
} else {
if (!isString(params)) {
formatDate && formatRequestDate(params);
if (
Reflect.has(config, 'data') &&
config.data &&
(Object.keys(config.data).length > 0 ||
config.data instanceof FormData)
) {
config.data = data;
config.params = params;
} else {
// 非GET请求如果没有提供data,则将params视为data
config.data = params;
config.params = undefined;
}

// 是否需要json对象转地址栏拼接
if (joinParamsToUrl) {
config.url = setObjToUrlParams(
config.url as string,
Object.assign({}, config.params, config.data)
);
}
} else {
// 兼容restful风格
config.url = config.url + params;
config.params = undefined;
}
}
return config;
},
/**
* @description: 请求拦截器处理
*/
requestInterceptors: (config) => {
// 请求之前处理config

// aes加密
(config as Recordable).headers.key = getAesStr();

// token
const token = getToken();
if (token && (config as Recordable)?.requestOptions?.withToken !== false) {
(config as Recordable).headers.token = token;
}
return config;
},
};

/**
* @description: 请求代理
*/
const createHttpProxy = (opt?: Partial<CreateAxiosOptions>) => {
return new HttpService(
deepMerge({
timeout: 10 * 1000,
headers: { 'Content-Type': 'application/json;charset=UTF-8' },
transform: clone(transform),
requestOptions: {
// 默认将prefix 添加到url
joinPrefix: true,
// 需要对返回数据进行处理
isTransformResponse: true,
// post请求的时候添加参数到url
joinParamsToUrl: false,
// 格式化提交参数时间
formatDate: true,
// 接口地址
// apiUrl: import.meta.env.VITE_API_BASE_URL,
// 接口拼接地址
urlPrefix: import.meta.env.VITE_API_BASE_URL,
// 是否加入时间戳
joinTime: true,
// 是否携带token
withToken: true,
},
})
);
};

export const service = createHttpProxy();

interceptors.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import type { RequestOptions, Result } from '@/types/axios';

export interface CreateAxiosOptions extends AxiosRequestConfig {
authenticationScheme?: string;
transform?: AxiosTransform;
requestOptions?: RequestOptions;
}

export abstract class AxiosTransform {
/**
* @description: Process configuration before request
*/
beforeRequestHook?: (config: AxiosRequestConfig, options: RequestOptions) => AxiosRequestConfig;

/**
* @description: 处理响应数据
*/
transformResponseHook?: (res: AxiosResponse<Result>, options: RequestOptions) => any;

/**
* @description: 请求失败处理
*/
requestCatchHook?: (e: Error, options: RequestOptions) => Promise<any>;

/**
* @description: 请求之前的拦截器
*/
requestInterceptors?: (
config: AxiosRequestConfig,
options: CreateAxiosOptions,
) => AxiosRequestConfig;

/**
* @description: 请求之后的拦截器
*/
responseInterceptors?: (res: AxiosResponse<any>) => AxiosResponse<any>;

/**
* @description: 请求之前的拦截器错误处理
*/
requestInterceptorsCatch?: (error: Error) => void;

/**
* @description: 请求之后的拦截器错误处理
*/
responseInterceptorsCatch?: (axiosInstance: AxiosResponse, error: Error) => void;
}

axios.d.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
export interface RequestOptions {
joinParamsToUrl?: boolean;
formatDate?: boolean;
isTransformResponse?: boolean;
isReturnNativeResponse?: boolean;
joinPrefix?: boolean;
apiUrl?: string;
urlPrefix?: string;
joinTime?: boolean;
withToken?: boolean;
}

export interface Result<T = any> {
code: number;
success: boolean;
msg: string;
retObj: T;
}

export interface UploadFileParams {
data?: Recordable;
name?: string;
file: File | Blob;
filename?: string;
[key: string]: any;
}

Api调用

1
2
3
export function 方法名(data: 入参类型) {
return service.post({ url: 'url地址', data });
}