request.ts
6.16 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
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 "./adapter";
import { dispatchEvent } from "./events";
import { sendRequestWithRetry } from "./retry";
import { addMethodAliases } from "./methods";
import {
preloadWhitelist,
checkWhitelist,
isWhitelistPreloaded,
} from "./whitelist";
import { subscribeEvents } from "./events";
import Trace from "./traces";
import Defaults from "./defaults";
import { initSentry, reportNetworkError } from "./sentry";
import { buildURL } from "./adapter/utils";
interface Interceptors {
request: InterceptorManager<RequestConfig>;
response: InterceptorManager<ResponseData>;
}
class Request {
defaults: Defaults;
interceptors: Interceptors;
private adapter: Adapter;
private signFunc: (options: SignatureOptions) => SignatureResult;
/**
* 获取白名单预加载状态
* @returns 白名单是否已预加载
*/
static get isWhitelistPreloaded(): boolean {
return isWhitelistPreloaded();
}
/**
* 获取跟踪管理器实例
* @returns 跟踪管理器实例
*/
static get _traceManager() {
return Trace;
}
constructor(config: RequestConfig) {
this.defaults = new Defaults(config);
// 创建拦截器实例
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager(),
};
// 在初始化时获取适合当前环境的适配器,并传递httpOptions参数
this.adapter = getAdapter(config.httpOptions);
// 在初始化时确定签名函数
this.signFunc = (function (config: RequestConfig) {
// 如果用户提供了自定义签名函数,则使用它,否则使用默认签名函数
return config.signatureFunc || generateSignature;
})(this.defaults);
// 自动订阅事件
subscribeEvents(this.defaults.events);
// 预加载白名单URL列表
preloadWhitelist();
// 初始化 Sentry
initSentry(this.defaults.sentryDsn, this.defaults.sentryOptions || {});
}
/**
* 发起请求
* @param options 请求配置
* @returns 可取消的请求Promise
*/
request<T = any>(
options: RequestConfig = {}
): Promise<ResponseData<T>> & { abort?: () => void } {
console.log("🚀 ~ Request ~ request ~ options:", options);
// 合并配置
const config = this.defaults.merge(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}
*/
async dispatchRequest<T = any>(
config: RequestConfig
): Promise<ResponseData<T>> {
// 添加签名
const signedConfig = await this.addSignature(config);
// 触发request事件
try {
const eventData = {
url: signedConfig.url,
method: signedConfig.method,
params: signedConfig.params,
data: signedConfig.data,
headers: signedConfig.headers,
};
// 触发request事件
dispatchEvent("request", eventData, signedConfig);
} catch (error) {
console.error("触发request事件失败:", error);
}
// 使用预先确定的适配器,并添加重试逻辑
return sendRequestWithRetry(this.adapter, signedConfig) as Promise<
ResponseData<T>
>;
}
/**
* 添加签名信息
* @param {Object} config 请求配置
* @returns {Object} 添加签名后的配置
*/
async addSignature(config: RequestConfig): Promise<RequestConfig> {
const { appId, appSecret } = config;
if (!appId || !appSecret) {
console.warn("缺少签名所需的应用ID或密钥");
return config;
}
// 获取请求参数
const params = { ...config.params };
// 检查当前请求的URL是否在白名单中
const isInWhitelist = await checkWhitelist(config.url!);
// 如果URL在白名单中,将sdctag=true添加到URL和签名参数中
if (isInWhitelist) {
// 检查URL是否已经包含查询参数
params.sdctag = "true";
}
config.params = params;
// 合并URL参数和请求体数据用于签名
const signatureParams = { ...config.params };
if (config.data && typeof config.data === "object") {
Object.assign(signatureParams, config.data);
}
// 使用预先确定的签名函数
const signature = this.signFunc({
appId,
appSecret,
params: signatureParams,
method: config.method || "POST",
});
// 添加签名到请求头
config.headers = {
...config.headers,
"X-App-Id": appId,
"X-Nonce": signature.nonce,
"X-Timestamp": signature.timestamp,
"X-Sign": signature.sign,
};
return config;
}
}
// 添加HTTP方法别名
addMethodAliases(Request.prototype);
export default Request;