-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
176 lines (156 loc) · 5.76 KB
/
Copy pathserver.ts
File metadata and controls
176 lines (156 loc) · 5.76 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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import dotenv from "dotenv";
dotenv.config({ override: true });
// Auto-map Gemini key variations for maximum robustness
process.env.GOOGLE_GENERATIVE_AI_API_KEY =
process.env.GEMINI_API_KEY || process.env.GOOGLE_GENERATIVE_AI_KEY;
import express from "express";
import path from "path";
import { handleTutorRequest } from "./src/server/tutor";
import { handleNcdcNewsRequest } from "./src/server/ncdc-news";
import { handleDynamicNotesRequest } from "./src/server/dynamic-notes";
import { handleEmailRequest } from "./src/server/email-router";
import { handleAttendanceRequest } from "./src/server/attendance";
async function startServer() {
console.log("[Boot] Current working directory:", process.cwd());
console.log("[Boot] GEMINI_API_KEY length:", process.env.GEMINI_API_KEY?.length || 0);
console.log(
"[Boot] GEMINI_API_KEY prefix:",
process.env.GEMINI_API_KEY ? process.env.GEMINI_API_KEY.substring(0, 15) : "none",
);
const app = express();
const PORT = 3000;
// Body parsers
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Helper to convert Express request to Web Request
function toWebRequest(req: express.Request): Request {
const protocol = req.protocol;
const host = req.get("host");
const url = new URL(req.originalUrl, `${protocol}://${host}`);
const body = ["POST", "PUT", "PATCH"].includes(req.method)
? JSON.stringify(req.body)
: undefined;
return new Request(url.toString(), {
method: req.method,
headers: new Headers(req.headers as any),
body,
});
}
// API Routes
app.get("/api/debug-env", (req, res) => {
res.json({
cwd: process.cwd(),
keys: Object.keys(process.env).filter(
(k) => k.includes("GEMINI") || k.includes("GOOGLE") || k.includes("API"),
),
geminiLength: process.env.GEMINI_API_KEY?.length || 0,
geminiPrefix: process.env.GEMINI_API_KEY
? process.env.GEMINI_API_KEY.substring(0, 15)
: "none",
});
});
app.post("/api/tutor", async (req, res) => {
console.log(`[API] POST /api/tutor from ${req.ip}`);
try {
const webReq = toWebRequest(req);
const response = await handleTutorRequest(webReq);
// Handle streaming responses
if (response.headers.get("Content-Type") === "text/event-stream") {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
const reader = response.body?.getReader();
if (reader) {
while (true) {
const { done, value } = await reader.read();
if (done) break;
res.write(value);
}
}
res.end();
} else {
const data = await response.json();
res.status(response.status).json(data);
}
} catch (error: any) {
console.error("Tutor API error:", error);
res.status(500).json({ error: error.message });
}
});
app.post("/api/ncdc-news", async (req, res) => {
console.log(`[API] POST /api/ncdc-news from ${req.ip}`);
try {
const webReq = toWebRequest(req);
const response = await handleNcdcNewsRequest(webReq);
const data = await response.json();
res.status(response.status).json(data);
} catch (error: any) {
console.error("NCDC News API error:", error);
res.status(500).json({ error: error.message });
}
});
app.post("/api/dynamic-notes", async (req, res) => {
console.log(`[API] POST /api/dynamic-notes from ${req.ip}`);
try {
const webReq = toWebRequest(req);
const response = await handleDynamicNotesRequest(webReq);
const data = await response.json();
res.status(response.status).json(data);
} catch (error: any) {
console.error("Dynamic Notes API error:", error);
res.status(500).json({ error: error.message });
}
});
app.post("/api/send-email", async (req, res) => {
try {
await handleEmailRequest(req, res);
} catch (error: any) {
console.error("Email API error:", error);
res.status(500).json({ error: error.message });
}
});
app.post("/api/attendance", async (req, res) => {
console.log(`[API] POST /api/attendance from ${req.ip}`);
try {
const webReq = toWebRequest(req);
const response = await handleAttendanceRequest(webReq);
const data = await response.json();
res.status(response.status).json(data);
} catch (error: any) {
console.error("Attendance API error:", error);
res.status(500).json({ error: error.message });
}
});
// Vite middleware for development
const isDev =
process.env.NODE_ENV === "development" ||
(!process.env.NODE_ENV && process.env.DISABLE_HMR !== "true");
console.log("[Boot] Mode:", isDev ? "development" : "production");
if (isDev) {
console.log("[Boot] Loading Vite in middlewareMode...");
const { createServer } = await import("vite");
console.log("[Boot] Importing vite succeeded. Creating server...");
const vite = await createServer({
server: { middlewareMode: true },
appType: "spa",
});
console.log("[Boot] Vite server created. Applying middlewares...");
app.use(vite.middlewares);
console.log("[Boot] Vite middlewares applied.");
} else {
console.log("[Boot] Serving production static files...");
const distPath = path.join(process.cwd(), "dist");
app.use(express.static(distPath));
app.get("*", (req, res) => {
res.sendFile(path.join(distPath, "index.html"));
});
}
console.log("[Boot] Starting to listen on port:", PORT);
app.listen(PORT, "0.0.0.0", () => {
console.log(`Server running on http://localhost:${PORT}`);
});
}
startServer().catch((err) => {
console.error("Failed to start server:", err);
process.exit(1);
});