request.ts
8.73 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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import InterceptorManager from './interceptor';
import { generateSignature, type SignatureOptions } from './signature';
import type { RequestConfig, ResponseData } from './types';
interface Interceptors {
request: InterceptorManager;
response: InterceptorManager;
}
interface MiniProgramRequestOptions {
url: string;
method: string;
header?: RequestConfig['headers'];
timeout?: number;
data?: any;
success: (res: any) => void;
fail: (err: any) => void;
}
interface MiniProgram {
request: (options: MiniProgramRequestOptions) => void;
}
declare const wx: MiniProgram | undefined;
class Request {
defaults: RequestConfig;
interceptors: Interceptors;
private adapter: (config: RequestConfig) => Promise<any>;
constructor(config: RequestConfig = {}) {
this.defaults = {
baseURL: '',
timeout: 5000,
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
appId: '',
appSecret: '',
...config
};
// 创建拦截器实例
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
// 在初始化时确定环境适配器
this.adapter = (function(that: Request) {
if (typeof wx !== 'undefined' && wx && 'request' in wx) {
// 小程序环境
return that.miniprogramAdapter.bind(that);
} else {
// Web环境
return that.webAdapter.bind(that);
}
})(this);
}
/**
* 发起请求
* @param {Object} options 请求配置
* @returns {Promise & {abort: Function}} 可取消的请求Promise
*/
request(options: RequestConfig = {}): Promise<any> & { abort?: () => void } {
// 合并配置
const config: RequestConfig = { ...this.defaults, ...options };
// 创建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(config: RequestConfig): Promise<any> {
// 添加签名
const signedConfig = this.addSignature(config);
// 使用预先确定的适配器
return this.adapter(signedConfig);
}
/**
* 添加签名信息
* @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 = generateSignature({
appId,
appSecret,
params
} as SignatureOptions);
// 添加签名到请求头
config.headers = {
...config.headers,
'X-App-Id': appId,
'X-Nonce': signature.nonce,
'X-Timestamp': signature.timestamp,
'X-Sign': signature.sign
};
return config;
}
/**
* Web环境适配器
* @param {Object} config 请求配置
* @returns {Promise}
*/
webAdapter(config: RequestConfig): Promise<any> {
const {
baseURL = '',
url = '',
method = 'GET',
headers = {},
params = {},
data = {},
timeout = 5000,
signal
} = config;
// 构建完整URL
let fullURL = baseURL + url;
// 处理GET请求参数
if (method.toUpperCase() === 'GET' && Object.keys(params).length) {
const queryString = Object.keys(params)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
.join('&');
fullURL += (fullURL.includes('?') ? '&' : '?') + queryString;
}
// 创建fetch选项
const fetchOptions: RequestInit & { timeout?: number } = {
method: method.toUpperCase(),
headers: headers as HeadersInit,
timeout
};
// 处理请求体
if (method.toUpperCase() !== 'GET' && Object.keys(data).length) {
if (headers['Content-Type'] && headers['Content-Type'].includes('application/json')) {
fetchOptions.body = JSON.stringify(data);
} else {
fetchOptions.body = data as BodyInit;
}
}
// 设置signal
if (signal) {
fetchOptions.signal = signal;
}
// 设置超时
let timeoutId: NodeJS.Timeout | null = null;
if (timeout && signal) {
// 只有当没有被取消时才设置超时
if (!signal.aborted) {
timeoutId = setTimeout(() => {
if (!signal.aborted) {
const event = new Event('abort');
signal.dispatchEvent(event);
}
}, timeout);
}
}
// 发起请求
return fetch(fullURL, fetchOptions)
.then(response => {
if (timeoutId) clearTimeout(timeoutId);
return response.json().catch(() => response.text());
})
.then(data => ({
data,
status: 200,
statusText: 'OK',
headers: {},
config
}))
.catch(error => {
if (timeoutId) clearTimeout(timeoutId);
// 处理取消请求的情况
if (error.name === 'AbortError' || (signal && signal.aborted)) {
throw new Error('请求已被取消');
}
throw error;
});
}
/**
* 小程序环境适配器
* @param {Object} config 请求配置
* @returns {Promise}
*/
miniprogramAdapter(config: RequestConfig): Promise<any> {
return new Promise((resolve, reject) => {
const {
baseURL = '',
url = '',
method = 'GET',
headers = {},
params = {},
data = {},
timeout = 5000
} = config;
// 构建完整URL
let fullURL = baseURL + url;
// 处理GET请求参数
if (method.toUpperCase() === 'GET' && Object.keys(params).length) {
const queryString = Object.keys(params)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
.join('&');
fullURL += (fullURL.includes('?') ? '&' : '?') + queryString;
}
// 小程序请求选项
const requestOption: MiniProgramRequestOptions = {
url: fullURL,
method: method.toUpperCase(),
header: headers,
timeout,
success: (res) => {
resolve({
data: res.data,
status: res.statusCode,
statusText: res.errMsg,
headers: res.header,
config
});
},
fail: (err) => {
reject(err);
}
};
// 处理请求体
if (method.toUpperCase() !== 'GET') {
requestOption.data = data;
}
// 发起请求
if (typeof wx !== 'undefined' && wx && 'request' in wx) {
wx.request(requestOption);
} else {
reject(new Error('当前环境不支持小程序请求'));
}
});
}
}
// 添加别名方法
(['get', 'post', 'put', 'delete', 'patch'] as const).forEach(method => {
(Request.prototype as any)[method] = function(url: string, dataOrConfig?: any, config: RequestConfig = {}) {
let finalConfig = { ...config };
// 根据方法类型处理参数
if (method === 'get' || method === 'delete') {
// 对于GET、DELETE方法,第二个参数是config
if (dataOrConfig) {
finalConfig = { ...finalConfig, ...dataOrConfig };
}
} else {
// 对于POST、PUT、PATCH方法,第二个参数是data,第三个参数是config
finalConfig.data = dataOrConfig;
}
return this.request({
url,
method: method.toUpperCase(),
...finalConfig
});
};
});
export default Request;