-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
71 lines (61 loc) · 1.76 KB
/
index.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
import { serve } from "https://deno.land/[email protected]/http/server.ts";
const getTodoList = () => {
const getLocal = localStorage.getItem("list");
const todoList: string[] = JSON.parse(getLocal || "[]");
return todoList;
};
const handlePost = async (req: Request) => {
const todoList = getTodoList();
const formData = await req.formData();
const todo = formData.get("todo")?.toString();
if (todo) {
todoList.push(todo);
localStorage.setItem("list", JSON.stringify(todoList));
}
return Response.redirect(req.url);
};
const handleGet = () => {
const todoList = getTodoList();
const renderView = todoList.map(
(val, index) =>
`<form action="/delete" method="POST">${val} <button type="submit" name="index" value="${index}">delete</button></form>`
);
return new Response(
`<form action="/" method="POST">
<input type="text" name="todo" placeholder="Add todo">
</form>
${renderView.join("")}`,
{
headers: {
"content-type": "text/html; charset=utf-8",
},
}
);
};
const handleDelete = async (req: Request) => {
const todoList = getTodoList();
const formData = await req.formData();
const index = formData.get("index")?.toString();
if (index) {
todoList.splice(parseInt(index), 1);
localStorage.setItem("list", JSON.stringify(todoList));
}
return Response.redirect(req.url.replace(/delete/, ""));
};
serve(async (req: Request) => {
if (req.method === "POST" && req.url.match(/delete/)) {
return await handleDelete(req);
}
if (req.method === "POST") {
return await handlePost(req);
}
if (req.method === "GET") {
return handleGet();
}
return new Response("404: Not Found!", {
status: 404,
headers: {
"content-type": "text/html; charset=utf-8",
},
});
});