-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxyFetch.ts
More file actions
190 lines (167 loc) · 5.26 KB
/
Copy pathproxyFetch.ts
File metadata and controls
190 lines (167 loc) · 5.26 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
// 扩展 XMLHttpRequest 接口以添加内部属性
declare global {
interface XMLHttpRequest {
_proxy?: {
method: string;
url: string;
headers: Record<string, string>;
};
}
}
// 定义用于 onRequest 回调的请求对象类型
export interface ProxyRequest {
method: string;
url: string;
body: XMLHttpRequestBodyInit | null | undefined;
setRequestHeader: (name: string, value: string) => void;
getHeaders?: () => Headers;
}
// 定义代理规则的类型
export interface ProxyRule {
match: (url: string, method: string) => boolean;
handler: (request: ProxyRequest) => Promise<ProxyRequest["body"]>;
}
// 定义配置选项的类型
export interface ProxyOptions {
rules: ProxyRule[];
}
let isProxyEnabled = false;
/**
* 设置 XMLHttpRequest 的代理
* @param {ProxyOptions} options
* @returns {() => void} restore 函数
*/
function setupXHRProxy(options: ProxyOptions): () => void {
// 保存原始的 XMLHttpRequest
const originalOpen = XMLHttpRequest.prototype.open;
const originalSend = XMLHttpRequest.prototype.send;
const originalSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
const defaultRules = [
{
match: (url: string, method: string) => url.includes("/api/resource/"),
handler: async (request: ProxyRequest) => {
return request.body;
},
},
];
XMLHttpRequest.prototype.open = function (method: string, url: string) {
this._proxy = { method, url, headers: {} };
originalOpen.apply(this, arguments as any);
};
XMLHttpRequest.prototype.setRequestHeader = function (
name: string,
value: string
) {
if (this._proxy) {
this._proxy.headers[name] = value;
}
originalSetRequestHeader.apply(this, arguments as any);
};
XMLHttpRequest.prototype.send = function (
body?: XMLHttpRequestBodyInit | null
) {
let modifiedBody: XMLHttpRequestBodyInit | null | undefined = body;
const request = this._proxy;
if (isProxyEnabled && request) {
const rules = options.rules ?? defaultRules;
const matchedRule = rules.find((rule) =>
rule.match(request.url, request.method)
);
if (matchedRule) {
const proxyHandler = async () => {
try {
const proxyRequest: ProxyRequest = {
method: request.method,
url: request.url,
body: body,
setRequestHeader: (name, value) =>
originalSetRequestHeader.call(this, name, value),
};
modifiedBody = await matchedRule.handler(proxyRequest);
} catch (e) {
console.error("[XHR Proxy] 代理规则执行失败:", e);
} finally {
originalSend.call(this, modifiedBody);
}
};
proxyHandler();
return; // 阻止同步发送
}
}
// 没有匹配规则或代理未启用,发送原始请求
originalSend.call(this, body);
};
return () => {
XMLHttpRequest.prototype.open = originalOpen;
XMLHttpRequest.prototype.send = originalSend;
XMLHttpRequest.prototype.setRequestHeader = originalSetRequestHeader;
};
}
/**
* 设置 Fetch API 的代理
* @param {ProxyOptions} options
* @returns {() => void} restore 函数
*/
function setupFetchProxy(options: ProxyOptions): () => void {
// 保存原始的 Fetch 方法
const originalFetch = window.fetch;
window.fetch = async function (
input: RequestInfo,
init?: RequestInit
): Promise<Response> {
const url = typeof input === "string" ? input : input.url;
const method = init?.method?.toUpperCase() || "GET";
if (isProxyEnabled) {
const matchedRule = options.rules.find((rule) => rule.match(url, method));
if (matchedRule) {
const headers = new Headers(init?.headers);
let body = init?.body;
const proxyRequest: ProxyRequest = {
method,
url,
body,
setRequestHeader: (name, value) => {
headers.set(name, value);
},
getHeaders: () => headers,
};
try {
body = await matchedRule.handler(proxyRequest);
} catch (e) {
console.error("[Fetch Proxy] 代理规则执行失败:", e);
}
const newInit = { ...init, headers, body, method };
return originalFetch(input, newInit);
}
}
// 没有匹配规则或代理未启用,发送原始请求
return originalFetch(input, init);
};
return () => {
window.fetch = originalFetch;
};
}
/**
* requestProxy 函数,作为代理功能的入口
* @param {ProxyOptions} options - 包含代理规则的配置对象。
* @returns {{restore: () => void}} 一个包含 restore 方法的对象。
*/
function requestProxy(options: ProxyOptions): { restore: () => void } {
if (isProxyEnabled) {
console.warn("requestProxy 已启用。请勿重复调用。");
return { restore: () => {} };
}
const restoreXHR = setupXHRProxy(options);
const restoreFetch = setupFetchProxy(options);
isProxyEnabled = true;
console.log("requestProxy 代理已启用。");
return {
restore: () => {
restoreXHR();
restoreFetch();
isProxyEnabled = false;
console.log("requestProxy 代理已禁用,原始方法已恢复。");
},
};
}
export default requestProxy;