Repository navigation
Expand file tree
/
Copy pathvite.config.ts
More file actions
101 lines (90 loc) · 2.56 KB
/
Copy pathvite.config.ts
File metadata and controls
101 lines (90 loc) · 2.56 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
import type { IncomingMessage, ServerResponse } from "node:http";
import { fileURLToPath, URL } from "node:url";
import tailwindcss from "@tailwindcss/vite";
import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import assistantHandler from "./api/assistant.ts";
function readRequestBody(req: IncomingMessage) {
return new Promise<string>((resolve, reject) => {
const chunks: Buffer[] = [];
req.on("data", (chunk) => {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
});
req.on("end", () => {
resolve(Buffer.concat(chunks).toString("utf8"));
});
req.on("error", reject);
});
}
function createJsonResponse(res: ServerResponse) {
let statusCode = 200;
return {
status(code: number) {
statusCode = code;
return this;
},
json(payload: unknown) {
res.statusCode = statusCode;
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.end(JSON.stringify(payload));
},
setHeader(name: string, value: string) {
res.setHeader(name, value);
},
write(chunk: string) {
res.write(chunk);
},
end(chunk?: string) {
res.end(chunk);
},
};
}
function localAssistantApiPlugin() {
return {
name: "local-assistant-api",
configureServer(server: {
middlewares: {
use(handler: (req: IncomingMessage, res: ServerResponse, next: () => void) => void): void;
};
}) {
server.middlewares.use(async (req, res, next) => {
if (!req.url?.startsWith("/api/assistant")) {
next();
return;
}
try {
const rawBody = await readRequestBody(req);
await assistantHandler(
{
method: req.method,
body: rawBody,
},
createJsonResponse(res),
);
} catch (error) {
console.error(error);
res.statusCode = 500;
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.end(
JSON.stringify({
error: "本地开发接口调用失败。",
code: "dev_server_error",
}),
);
}
});
},
};
}
export default defineConfig(({ mode }) => {
Object.assign(process.env, loadEnv(mode, process.cwd(), ""));
return {
plugins: [vue(), tailwindcss(), localAssistantApiPlugin()],
resolve: {
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url)),
"~": fileURLToPath(new URL("./src", import.meta.url)),
},
},
};
});