-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
75 lines (66 loc) · 1.9 KB
/
index.js
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
/** @typedef {import('@sveltejs/kit').Handle} Handle */
/**
* @param {{ [key: string]: string }} proxy
* @param {{ debug?: boolean; changeOrigin?: boolean }=} options
* @returns Handle
*/
export function proxyHandle(proxy, options = { changeOrigin: true }) {
return async function ({ event, resolve }) {
const { url, request } = event;
const { pathname, search } = url;
/**
* Find first matching path
*/
const matchingProxy = Object.keys(proxy).find((proxyPath) =>
pathname.match(proxyPath),
);
if (matchingProxy) {
const proxyTarget = proxy[matchingProxy];
/**
* Collect request headers
*/
const requestHeaders = new Headers(request.headers);
if (options && options.changeOrigin) {
requestHeaders.delete('host');
}
if (options && options.debug) {
console.debug(`Proxy: ${proxyTarget}${pathname}`, requestHeaders);
}
/**
* Fetch data from remote server
*/
try {
const response = await fetch(`${proxyTarget}${pathname}${search}`, {
redirect: 'manual',
method: request.method,
headers: requestHeaders,
});
/**
* Clean up response headers
*/
const responseHeaders = new Headers(response.headers);
responseHeaders.delete('content-encoding');
if (options && options.debug) {
console.debug(
`Proxy response (${response.status}) headers:`,
responseHeaders,
);
}
/**
* Return response from remote server
*/
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
});
} catch (error) {
console.error(error);
}
}
/**
* Proceed without proxy
*/
return await resolve(event);
};
}