-
Notifications
You must be signed in to change notification settings - Fork 523
/
Copy pathproxy-content.ts
46 lines (40 loc) · 1.4 KB
/
proxy-content.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
import {
createProxyMiddleware,
fixRequestBody,
responseInterceptor,
} from "http-proxy-middleware";
import { withContentResponseHeaders } from "../headers.js";
import { Source, sourceUri } from "../env.js";
import { PROXY_TIMEOUT } from "../constants.js";
import { isLiveSampleURL } from "../utils.js";
const NOT_FOUND_PATH = "en-us/_spas/404.html";
let notFoundBuffer: ArrayBuffer;
const target = sourceUri(Source.content);
export const proxyContent = createProxyMiddleware({
target,
changeOrigin: true,
autoRewrite: true,
proxyTimeout: PROXY_TIMEOUT,
xfwd: true,
selfHandleResponse: true,
onProxyReq: fixRequestBody,
onProxyRes: responseInterceptor(
async (responseBuffer, proxyRes, req, res) => {
withContentResponseHeaders(proxyRes, req, res);
if (proxyRes.statusCode === 404 && !isLiveSampleURL(req.url ?? "")) {
const tryHtml = await fetch(`${target}${req.url?.slice(1)}/index.html`);
if (tryHtml.ok) {
res.statusCode = 200;
res.setHeader("Content-Type", "text/html");
return Buffer.from(await tryHtml.arrayBuffer());
} else if (!notFoundBuffer) {
const response = await fetch(`${target}${NOT_FOUND_PATH}`);
notFoundBuffer = await response.arrayBuffer();
}
res.setHeader("Content-Type", "text/html");
return Buffer.from(notFoundBuffer);
}
return responseBuffer;
}
),
});