request.ts
7.01 KB
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
234
import InterceptorManager from './interceptor';
import { generateSignature, type SignatureOptions, type SignatureResult } from './signature';
import type { RequestConfig, ResponseData } from './types';
import { RequestError } from './error';
import { getAdapter, type Adapter } from './adapters';
interface Interceptors {
request: InterceptorManager<RequestConfig>;
response: InterceptorManager<ResponseData>;
}
class Request {
defaults: RequestConfig;
interceptors: Interceptors;
private adapter: Adapter;
private signFunc: (options: SignatureOptions) => SignatureResult;
constructor(config: RequestConfig = {}) {
this.defaults = {
baseURL: '',
timeout: 5000,
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
appId: '',
appSecret: '',
// 默认重试配置
retries: 0, // 默认不重试
retryDelay: 300, // 默认重试延迟300ms
shouldResetTimeout: true, // 默认重试时重置超时
...config
};
// 创建拦截器实例
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
// 在初始化时获取适合当前环境的适配器
this.adapter = getAdapter();
// 在初始化时确定签名函数
this.signFunc = (function(config: RequestConfig) {
// 如果用户提供了自定义签名函数,则使用它,否则使用默认签名函数
return config.signatureFunc || generateSignature;
})(this.defaults);
}
/**
* 发起请求
* @param {Object} options 请求配置
* @returns {Promise & {abort: Function}} 可取消的请求Promise
*/
request<T = any>(options: RequestConfig = {}): Promise<ResponseData<T>> & { abort?: () => void } {
// 合并配置
const config: RequestConfig = {
...this.defaults,
...options,
// 确保params正确合并
params: { ...this.defaults.params, ...options.params }
};
// 创建AbortController用于请求取消
const controller = new AbortController();
// 如果配置中已存在signal,则需要合并处理
if (config.signal) {
// 当外部signal触发abort时,也触发内部controller的abort
config.signal.addEventListener('abort', () => {
controller.abort();
});
}
// 将controller.signal设置到config中
config.signal = controller.signal;
// 创建请求链
const chain: Array<(value: any) => any | Promise<any> | undefined> = [this.dispatchRequest.bind(this), () => undefined];
// 添加请求拦截器
this.interceptors.request.forEach(interceptor => {
chain.unshift(interceptor.fulfilled, interceptor.rejected);
});
// 添加响应拦截器
this.interceptors.response.forEach(interceptor => {
chain.push(interceptor.fulfilled, interceptor.rejected);
});
// 执行请求链
let promise = Promise.resolve(config);
while (chain.length) {
promise = promise.then(chain.shift() as (value: any) => any, chain.shift() as (value: any) => any);
}
// 为Promise添加abort方法
const promiseWithAbort = promise as Promise<any> & { abort: () => void };
promiseWithAbort.abort = () => {
controller.abort();
};
return promiseWithAbort;
}
/**
* 处理请求分发
* @param {Object} config 请求配置
* @returns {Promise}
*/
dispatchRequest<T = any>(config: RequestConfig): Promise<ResponseData<T>> {
// 添加签名
const signedConfig = this.addSignature(config);
// 使用预先确定的适配器,并添加重试逻辑
return this.sendRequestWithRetry(signedConfig, 0) as Promise<ResponseData<T>>;
}
/**
* 发送请求并处理重试逻辑
* @param {RequestConfig} config 请求配置
* @param {number} retryCount 当前重试次数
* @returns {Promise}
*/
private sendRequestWithRetry(config: RequestConfig, retryCount: number): Promise<ResponseData<any>> {
const { retries = 0, retryDelay = 300, retryCondition } = config;
return this.adapter(config).catch((error: RequestError) => {
// 判断是否需要重试
const shouldRetry = (
// 未超过最大重试次数
retryCount < retries &&
// 如果有自定义重试条件,则使用自定义条件判断
(retryCondition ? retryCondition(error) : this.isRetryableError(error))
);
if (shouldRetry) {
console.log(`请求失败,正在进行第${retryCount + 1}次重试...`);
// 创建延迟Promise
const delayPromise = new Promise(resolve => {
setTimeout(resolve, retryDelay);
});
// 延迟后重试
return delayPromise.then(() => {
// 如果需要重置超时,则重新创建一个新的AbortController
if (config.shouldResetTimeout && config.timeout) {
const controller = new AbortController();
config.signal = controller.signal;
}
return this.sendRequestWithRetry(config, retryCount + 1);
});
}
// 不需要重试,直接抛出错误
throw error;
});
}
/**
* 判断错误是否可重试
* @param {RequestError} error 错误对象
* @returns {boolean} 是否可重试
*/
private isRetryableError(error: RequestError): boolean {
// 网络错误、服务器错误(5xx)可以重试
// 请求被取消、客户端错误(4xx)不重试
return (
error.code === 'NETWORK_ERROR' ||
(error.response && error.response.status >= 500 && error.response.status < 600)
);
}
/**
* 添加签名信息
* @param {Object} config 请求配置
* @returns {Object} 添加签名后的配置
*/
addSignature(config: RequestConfig): RequestConfig {
const { appId, appSecret } = config;
if (!appId || !appSecret) {
console.warn('缺少签名所需的应用ID或密钥');
return config;
}
// 获取请求参数
const params = { ...config.params };
// 使用预先确定的签名函数
const signature = this.signFunc({ appId, appSecret, params });
// 添加签名到请求头
config.headers = {
...config.headers,
'X-App-Id': appId,
'X-Nonce': signature.nonce,
'X-Timestamp': signature.timestamp,
'X-Sign': signature.sign
};
return config;
}
}
// 添加别名方法
(['get', 'post', 'put', 'delete', 'patch'] as const).forEach(method => {
if (method === 'get' || method === 'delete') {
// 对于GET、DELETE方法
(Request.prototype as any)[method] = function(url: string, config: RequestConfig = {}) {
return this.request({
url,
method: method.toUpperCase(),
...config
});
};
} else {
// 对于POST、PUT、PATCH方法
(Request.prototype as any)[method] = function(url: string, data?: any, config: RequestConfig = {}) {
return this.request({
url,
method: method.toUpperCase(),
data,
...config
});
};
}
});
export default Request;