-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
99 lines (87 loc) · 2.33 KB
/
main.ts
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
import {
Application,
Router,
Context,
} from "https://deno.land/x/oak@v12.6.1/mod.ts";
import { config } from "https://deno.land/x/dotenv@v3.2.2/mod.ts";
import { renderFileToString } from "https://deno.land/x/dejs@0.10.3/mod.ts";
import {
join,
dirname,
fromFileUrl,
} from "https://deno.land/std@0.204.0/path/mod.ts";
import { oakCors } from "https://deno.land/x/cors@v1.2.2/mod.ts";
import { handleAIAssist } from "./aiAssist.ts";
// Load environment variables
await config({ export: true });
const __dirname = dirname(fromFileUrl(import.meta.url));
// Helper function to log environment variables
function logEnvironmentVariables(...variables: string[]) {
variables.forEach((variable) => {
console.log(`${variable}:`, Deno.env.get(variable) ? "Set" : "Not set");
});
}
logEnvironmentVariables(
"OPENROUTER_API_KEY",
"OPENROUTER_API_KEY2",
"OPENROUTER_API_KEY3",
"YOUR_SITE_URL",
"YOUR_SITE_NAME",
);
const app = new Application();
const router = new Router();
// Middleware
app.use(
oakCors({
origin: Deno.env.get("ALLOWED_ORIGINS")?.split(",") || "*",
optionsSuccessStatus: 200,
}),
);
app.use(errorHandler);
// Serve static files
app.use(async (ctx, next) => {
try {
await ctx.send({
root: join(__dirname, "public"),
index: "index.html",
maxage: 86400000, // 1 day in milliseconds
});
} catch {
await next();
}
});
// Route handlers
async function handleIndex(ctx: Context) {
const content = await renderFileToString(
join(__dirname, "views", "index.ejs"),
);
ctx.response.body = content;
ctx.response.type = "text/html";
}
// Routes
router.get("/", handleIndex);
router.post("/ai-assist", handleAIAssist);
app.use(router.routes());
app.use(router.allowedMethods());
// Error handling middleware
async function errorHandler(ctx: Context, next: () => Promise<unknown>) {
try {
await next();
} catch (err) {
console.error("Unhandled error:", err);
ctx.response.status = 500;
ctx.response.body = { error: "Internal server error" };
}
}
// Start server
const port = 3000;
console.log(`Server running on http://localhost:${port}`);
try {
await app.listen({ port });
} catch (error) {
if (error instanceof Deno.errors.BadResource) {
console.error("Connection error:", error.message);
} else {
console.error("Unexpected error:", error);
}
}