-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
sendProxyReq.ts
65 lines (54 loc) · 1.54 KB
/
sendProxyReq.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
// deno-lint-ignore-file no-explicit-any
import type { ProxyState } from "../createState.ts";
export class TimeoutError extends Error {
code = "ECONTIMEDOUT";
name = "TimeoutError";
ok = false;
redirected = false;
status = 408;
statusText = "ECONTIMEDOUT";
type = "error";
constructor(public message: string = "TimeoutError", public url?: string) {
super(message);
}
static type() {
return this.name;
}
}
export function sendProxyReq(state: ProxyState) {
const url = state.proxy.url as URL;
const reqInit = state.proxy.reqInit;
const timeout = state.options.timeout;
const isTimeout = typeof timeout === "number";
if (reqInit.method === "GET" || reqInit.method === "HEAD") {
reqInit.body = undefined;
}
// TODO: use AbortController - blocked by https://github.com/denoland/deno/pull/6093.
let timeoutId: number;
return Promise.all<any>([
fetch(url, reqInit).then((res) => {
if (isTimeout) clearTimeout(timeoutId);
return res;
}),
...(isTimeout
? [
new Promise((_resolve, reject) => {
timeoutId = setTimeout(
() => reject(new TimeoutError(TimeoutError.type(), url.toString())),
timeout,
);
}),
]
: []),
]).then(async ([res]: Response[]) => {
state.proxy.res = res;
if (state.options.stream) {
return state;
}
const bufferedResponse = await res.arrayBuffer();
state.proxy.resData = bufferedResponse === null
? null
: new Uint8Array(bufferedResponse);
return state;
});
}