-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodos.js
77 lines (64 loc) · 1.8 KB
/
todos.js
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
import express from "express";
import { neon } from "@neondatabase/serverless";
import todoTemplate from "./todo-template.js";
import cookieParser from "cookie-parser";
const getDb = (authToken) =>
neon(process.env.DATABASE_AUTHENTICATED_URL, { authToken });
const router = express.Router();
router.use(cookieParser());
async function getTodos(token) {
const sql = getDb(token);
const rows = await sql`
SELECT * FROM todos;
`;
return rows.map((row) => todoTemplate(row));
}
router.get("/", async (req, res) => {
const token = req.cookies.__token_jwt;
if (!token) {
return res.status(401).send("Unauthorized");
}
const todos = await getTodos(token);
res.send(todos.join(""));
});
router.post("/", async (req, res) => {
const token = req.cookies.__token_jwt;
if (!token) {
return res.status(401).send("Unauthorized");
}
const sql = getDb(token);
await sql`
INSERT INTO todos (title, done, user_id)
VALUES (${req.body.title}, false, auth.user_id());
`;
const todos = await getTodos(token);
res.send(todos.join(""));
});
router.post("/:id/toggle", async (req, res) => {
const token = req.cookies.__token_jwt;
if (!token) {
return res.status(401).send("Unauthorized");
}
const sql = getDb(token);
await sql`
UPDATE todos
SET done = NOT done
WHERE id = ${req.params.id} AND user_id = auth.user_id();
`;
const todos = await getTodos(token);
res.send(todos.join(""));
});
router.delete("/:id", async (req, res) => {
const token = req.cookies.__token_jwt;
if (!token) {
return res.status(401).send("Unauthorized");
}
const sql = getDb(token);
await sql`
DELETE FROM todos
WHERE id = ${req.params.id} AND user_id = auth.user_id();
`;
const todos = await getTodos(token);
res.send(todos.join(""));
});
export default router;