-
Notifications
You must be signed in to change notification settings - Fork 218
/
proxy.ts
171 lines (157 loc) · 4.08 KB
/
proxy.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
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
import type { H3EventContext, H3Event, ProxyOptions, Duplex } from "../types";
import { splitSetCookieString } from "cookie-es";
import { sanitizeStatusMessage, sanitizeStatusCode } from "./sanitize";
import { createError } from "../error";
import {
PayloadMethods,
getFetch,
ignoredHeaders,
mergeHeaders,
rewriteCookieProperty,
} from "./internal/proxy";
import { EmptyObject } from "./internal/obj";
/**
* Proxy the incoming request to a target URL.
*/
export async function proxyRequest(
event: H3Event,
target: string,
opts: ProxyOptions = {},
) {
// Request Body
let body;
let duplex: Duplex | undefined;
if (PayloadMethods.has(event.request.method)) {
if (opts.streamRequest) {
body = event.request.body;
duplex = "half";
} else {
body = await event.request.arrayBuffer();
}
}
// Method
const method = opts.fetchOptions?.method || event.request.method;
// Headers
const fetchHeaders = mergeHeaders(
getProxyRequestHeaders(event),
opts.fetchOptions?.headers,
opts.headers,
);
return proxy(event, target, {
...opts,
fetchOptions: {
method,
body,
duplex,
...opts.fetchOptions,
headers: fetchHeaders,
},
});
}
/**
* Make a proxy request to a target URL and send the response back to the client.
*/
export async function proxy(
event: H3Event,
target: string,
opts: ProxyOptions = {},
): Promise<BodyInit | undefined | null> {
let response: Response | undefined;
try {
response = await getFetch(opts.fetch)(target, {
headers: opts.headers as HeadersInit,
ignoreResponseError: true, // make $ofetch.raw transparent
...opts.fetchOptions,
});
} catch (error) {
throw createError({
status: 502,
statusMessage: "Bad Gateway",
cause: error,
});
}
event.response.status = sanitizeStatusCode(
response.status,
event.response.status,
);
event.response.statusText = sanitizeStatusMessage(response.statusText);
const cookies: string[] = [];
for (const [key, value] of response.headers.entries()) {
if (key === "content-encoding") {
continue;
}
if (key === "content-length") {
continue;
}
if (key === "set-cookie") {
cookies.push(...splitSetCookieString(value));
continue;
}
event.response.headers.set(key, value);
}
if (cookies.length > 0) {
const _cookies = cookies.map((cookie) => {
if (opts.cookieDomainRewrite) {
cookie = rewriteCookieProperty(
cookie,
opts.cookieDomainRewrite,
"domain",
);
}
if (opts.cookiePathRewrite) {
cookie = rewriteCookieProperty(cookie, opts.cookiePathRewrite, "path");
}
return cookie;
});
for (const cookie of _cookies) {
event.response.headers.append("set-cookie", cookie);
}
}
if (opts.onResponse) {
await opts.onResponse(event, response);
}
// Directly send consumed _data
if ((response as any)._data !== undefined) {
return (response as any)._data;
}
// Send at once
if (opts.sendStream === false) {
return new Uint8Array(await response.arrayBuffer());
}
// Send as stream
return response.body;
}
/**
* Get the request headers object without headers known to cause issues when proxying.
*/
export function getProxyRequestHeaders(event: H3Event) {
const headers = new EmptyObject();
for (const [name, value] of event.request.headers.entries()) {
if (!ignoredHeaders.has(name)) {
headers[name] = value;
}
}
return headers;
}
/**
* Make a fetch request with the event's context and headers.
*/
export function fetchWithEvent<
T = unknown,
_R = unknown,
F extends (req: RequestInfo | URL, opts?: any) => any = typeof fetch,
>(
event: H3Event,
req: RequestInfo | URL,
init?: RequestInit & { context?: H3EventContext },
options?: { fetch: F },
): unknown extends T ? ReturnType<F> : T {
return getFetch(options?.fetch)(req, <RequestInit>{
...init,
context: init?.context || event.context,
headers: {
...getProxyRequestHeaders(event),
...init?.headers,
},
});
}