This repository has been archived by the owner on Oct 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.ts
56 lines (51 loc) · 1.57 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
import { Deta } from "npm:deta";
const deta = Deta();
const handler = async (request: Request): Promise<Response> => {
const url = new URL(request.url);
switch (url.pathname) {
case "/": {
// Serve a static HTML file
const body = new TextDecoder().decode(
Deno.readFileSync("./static/index.html")
);
return new Response(body, {
status: 200,
headers: { "Content-Type": "text/html" },
});
}
case "/api/todos": {
// Connect to a Base for storing todo items.
const todos_base = deta.Base("todos");
if (request.method === "GET") {
// Fetch all items from the Base.
const todos = await todos_base.fetch();
// Return the items as JSON.
return Response.json(todos.items, {
status: 200,
headers: { "Content-Type": "application/json" },
});
} else if (request.method === "POST") {
// Get the item from the request body.
const item = await request.json();
// Put the item into the Base.
const resp = await todos_base.put(item);
// Return the response as JSON.
return Response.json(resp, {
status: 201,
headers: { "Content-Type": "application/json" },
});
} else {
// If the request method is not GET or POST, return a 405 error
return new Response("Method Not Allowed", { status: 405 });
}
}
default:
return new Response("Not Found", { status: 404 });
}
};
Deno.serve(
{
port: parseInt(Deno.env.get("PORT") || "8080"),
},
handler
);