-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.cjs
More file actions
83 lines (71 loc) · 2.24 KB
/
index.cjs
File metadata and controls
83 lines (71 loc) · 2.24 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
const path = require("node:path");
const server = require("fastify")({ logger: true });
server.register(require("@fastify/static"), {
root: path.join(__dirname, "static"),
});
server.get("/health", async () => "OK");
server.listen({ port: 8080, host: "0.0.0.0" }, (err) => {
if (err) throw err;
});
const proxy = async (request, reply) => {
try {
// Add CORS headers
reply.header("Access-Control-Allow-Origin", "*");
reply.header(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS",
);
reply.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
// Handle preflight requests
if (request.method === "OPTIONS") {
reply.status(200).send();
return;
}
const targetPath = request.params["*"];
const queryString = request.url.includes("?")
? request.url.substring(request.url.indexOf("?"))
: "";
const targetUrl = targetPath + queryString;
// Prepare request options
const fetchOptions = {
method: request.method,
headers: {
"User-Agent": "Elm-Playground-Proxy/1.0",
},
redirect: "follow",
};
// Add body for POST/PUT requests
if (request.method !== "GET" && request.method !== "HEAD") {
fetchOptions.body = request.body;
}
const response = await fetch(targetUrl, fetchOptions);
const contentType = response.headers.get("content-type");
reply.header("Content-Type", contentType);
// For JSON responses, forward all to proxy – leave rest as is
if (contentType?.includes("json")) {
const rawJson = await response
.text()
.then((raw) => raw.replace("https://", "/proxy/https://"));
reply.send(rawJson);
} else {
const buffer = await response.arrayBuffer();
const body = Buffer.from(buffer);
reply.send(body);
}
} catch (error) {
console.error("Proxy error:", error);
reply.status(500);
reply.send({ error: "Proxy request failed" });
}
};
server.get("/proxy/*", proxy);
server.post("/proxy/*", proxy);
server.options("/proxy/*", proxy);
const PUBLIC_URL = process.env.PUBLIC_URL;
if (PUBLIC_URL) {
const keepAlive = () => {
fetch(`${PUBLIC_URL}/health`);
setTimeout(keepAlive, 10 * 1000);
};
keepAlive();
}