-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvite.config.ts
More file actions
145 lines (121 loc) · 3.92 KB
/
Copy pathvite.config.ts
File metadata and controls
145 lines (121 loc) · 3.92 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
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
import type { IncomingMessage, ServerResponse } from "node:http";
import { defineConfig, loadEnv, type ViteDevServer } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig(({ mode }) => {
Object.assign(process.env, loadEnv(mode, process.cwd(), ""));
return {
plugins: [react(), vercelApiDevPlugin()],
};
});
function vercelApiDevPlugin() {
return {
name: "grabmaps-vercel-api-dev",
configureServer(server: ViteDevServer) {
server.middlewares.use(async (req, res, next) => {
const url = new URL(req.url ?? "/", "http://localhost");
const route = resolveApiRoute(url.pathname);
if (!route) {
next();
return;
}
try {
const body = await readRequestBody(req);
const query = toVercelQuery(url.searchParams);
if (route.params) Object.assign(query, route.params);
const reqLike = Object.assign(req, {
body,
query,
method: req.method,
});
const resLike = createVercelResponse(res);
const mod = await server.ssrLoadModule(route.modulePath);
await mod.default(reqLike, resLike);
} catch (error) {
if (!res.headersSent) {
res.statusCode = 500;
res.setHeader("Content-Type", "application/json");
}
res.end(JSON.stringify({ error: error instanceof Error ? error.message : "Local API failed" }));
}
});
},
};
}
function resolveApiRoute(pathname: string) {
const routes: Record<string, string> = {
"/api/map/style": "/api/map/style.ts",
"/api/map/proxy": "/api/map/proxy.ts",
"/api/poi/search": "/api/poi/search.ts",
"/api/poi/nearby": "/api/poi/nearby.ts",
"/api/poi/details": "/api/poi/details.ts",
"/api/route": "/api/route.ts",
"/api/reviews": "/api/reviews.ts",
"/api/voice/tts": "/api/voice/tts.ts",
"/api/chat": "/api/chat.ts",
"/api/personality/duel": "/api/personality/duel.ts",
};
if (routes[pathname]) {
return { modulePath: routes[pathname] };
}
const personalityMatch = pathname.match(/^\/api\/personality\/([^/]+)$/);
if (personalityMatch) {
return {
modulePath: "/api/personality/[id].ts",
params: { id: decodeURIComponent(personalityMatch[1]) },
};
}
return null;
}
function toVercelQuery(searchParams: URLSearchParams) {
const query: Record<string, string | string[]> = {};
for (const [key, value] of searchParams) {
const existing = query[key];
if (Array.isArray(existing)) {
existing.push(value);
} else if (typeof existing === "string") {
query[key] = [existing, value];
} else {
query[key] = value;
}
}
return query;
}
async function readRequestBody(req: IncomingMessage) {
if (req.method === "GET" || req.method === "HEAD") return undefined;
const chunks: Buffer[] = [];
for await (const chunk of req) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
}
if (!chunks.length) return undefined;
const raw = Buffer.concat(chunks).toString("utf8");
const contentType = req.headers["content-type"] ?? "";
if (contentType.includes("application/json")) {
return raw ? JSON.parse(raw) : undefined;
}
return raw;
}
function createVercelResponse(res: ServerResponse) {
const resLike = res as ServerResponse & {
status: (code: number) => typeof resLike;
json: (payload: unknown) => void;
send: (payload: unknown) => void;
};
resLike.status = (code: number) => {
res.statusCode = code;
return resLike;
};
resLike.json = (payload: unknown) => {
if (!res.headersSent) {
res.setHeader("Content-Type", "application/json");
}
res.end(JSON.stringify(payload));
};
resLike.send = (payload: unknown) => {
if (Buffer.isBuffer(payload) || typeof payload === "string") {
res.end(payload);
return;
}
resLike.json(payload);
};
return resLike;
}