-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
35 lines (31 loc) · 1.09 KB
/
index.ts
File metadata and controls
35 lines (31 loc) · 1.09 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
const yesReasons = await Bun.file("yes.json").json();
const noReasons = await Bun.file("no.json").json();
const getRandom = (arr: string[]) =>
arr[Math.floor(Math.random() * arr.length)];
const routes: Record<string, (req: Request) => Response> = {
"/yes": () =>
new Response(JSON.stringify({ reason: getRandom(yesReasons) }), {
headers: { "Content-Type": "application/json" },
}),
"/no": () =>
new Response(JSON.stringify({ reason: getRandom(noReasons) }), {
headers: { "Content-Type": "application/json" },
}),
"/": () =>
new Response(
JSON.stringify({ reason: "Welcome to the Yes/No API! Try /yes or /no" }),
{ headers: { "Content-Type": "application/json" } }
),
};
Bun.serve({
port: 3000,
fetch(req) {
const handler = routes[new URL(req.url).pathname];
if (handler && req.method === "GET") return handler(req);
return new Response(JSON.stringify({ reason: "Not Found" }), {
headers: { "Content-Type": "application/json" },
status: 404,
});
},
});
console.log("Yes/No Reason API is running on http://localhost:3000");