-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaxiosInstance.ts
109 lines (96 loc) · 2.87 KB
/
axiosInstance.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
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import qs from "qs";
interface Config {
env: string;
baseURL: string;
}
interface GetParams {
[key: string]: any;
}
interface PostData {
[key: string]: any;
}
interface DeleteParams {
[key: string]: any;
}
// 配置列表
const configs: Config[] = [
{ env: "development", baseURL: "https://www.development.com" },
{ env: "debug", baseURL: "https://www.debug.com" },
{ env: "production", baseURL: "https://www.production.com" },
];
// 创建 Axios 实例
function createAxiosInstance(config: Config): AxiosInstance {
return axios.create({
baseURL: config.baseURL,
timeout: 10000,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
});
}
// 获取 Axios 实例
function getAxiosInstance(env: string): AxiosInstance {
// @ts-ignore
const selectedConfig = configs.find((cfg) => cfg.env === env);
if (!selectedConfig) {
throw new Error(`No configuration found for environment "${env}".`);
}
return createAxiosInstance(selectedConfig);
}
// 请求方法工厂
const createHttpMethod = <P = any, R = any>(method: "get" | "post" | "delete", instance: AxiosInstance) => {
return (url: string, dataOrParams?: P, config?: AxiosRequestConfig) => {
const controller = new AbortController();
const signal = controller.signal;
const res = async () => {
try {
const paramsOrData = qs.stringify(dataOrParams);
let response: AxiosResponse<R>;
switch (method) {
case "get":
response = await instance.get<R>(url, {
params: paramsOrData,
signal,
...config,
});
break;
case "post":
response = await instance.post<R>(url, paramsOrData, {
signal,
...config,
});
break;
case "delete":
response = await instance.delete<R>(url, {
params: paramsOrData,
signal,
...config,
});
break;
default:
throw new Error(`Unsupported HTTP method: ${method}`);
}
return response;
} catch (error) {
if (axios.isCancel(error)) {
console.log(`${method.toUpperCase()} request canceled:`, error.message);
} else {
console.error(`${method.toUpperCase()} request error:`, error);
throw error;
}
}
};
return { res, cancel: () => controller.abort() };
};
};
// 封装请求的对象
const createHttpRequests = (env: string) => {
const instance = getAxiosInstance(env);
return {
get: createHttpMethod<GetParams, any>(instance, "get"),
post: createHttpMethod<PostData, any>(instance, "post"),
delete: createHttpMethod<DeleteParams, any>(instance, "delete"),
};
};
export default createHttpRequests;