-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite.config.ts
More file actions
104 lines (96 loc) · 2.78 KB
/
Copy pathvite.config.ts
File metadata and controls
104 lines (96 loc) · 2.78 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import { defineConfig, type Plugin } from "vite";
import react from "@vitejs/plugin-react";
import type { IncomingMessage, ServerResponse } from "node:http";
function readBody(req: IncomingMessage): Promise<string> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
req.on("data", (c) => chunks.push(Buffer.from(c)));
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
req.on("error", reject);
});
}
function apiProxyPlugin(): Plugin {
const handler = async (req: IncomingMessage, res: ServerResponse) => {
if (req.method === "OPTIONS") {
res.statusCode = 204;
res.end();
return;
}
try {
const raw = await readBody(req);
const payload = JSON.parse(raw || "{}") as {
url?: string;
method?: string;
headers?: Record<string, string>;
body?: string;
};
if (!payload.url) {
res.statusCode = 400;
res.setHeader("content-type", "application/json");
res.end(JSON.stringify({ error: "url required" }));
return;
}
const headers = { ...(payload.headers || {}) };
// Never forward hop-by-hop / browser-only headers
delete headers["host"];
delete headers["origin"];
delete headers["referer"];
delete headers["content-length"];
const upstream = await fetch(payload.url, {
method: payload.method || "GET",
headers,
body:
payload.body &&
!["GET", "HEAD"].includes((payload.method || "GET").toUpperCase())
? payload.body
: undefined,
});
const text = await upstream.text();
let body: unknown = text;
try {
body = JSON.parse(text);
} catch {
/* keep text */
}
const outHeaders: Record<string, string> = {};
upstream.headers.forEach((v, k) => {
outHeaders[k] = v;
});
res.statusCode = 200;
res.setHeader("content-type", "application/json");
res.end(
JSON.stringify({
status: upstream.status,
headers: outHeaders,
body,
}),
);
} catch (e) {
res.statusCode = 500;
res.setHeader("content-type", "application/json");
res.end(
JSON.stringify({
status: 0,
error: e instanceof Error ? e.message : "proxy failed",
body: null,
}),
);
}
};
return {
name: "chisel-api-proxy",
configureServer(server) {
server.middlewares.use("/api/proxy", (req, res) => {
void handler(req, res);
});
},
configurePreviewServer(server) {
server.middlewares.use("/api/proxy", (req, res) => {
void handler(req, res);
});
},
};
}
export default defineConfig({
plugins: [react(), apiProxyPlugin()],
});