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
|
import { Router } from "express";
import db from "../db.js";
import type { User } from "../types.js";
const router = Router();
export const getUser = (userId: User["id"]) => {
const byId = db.prepare("SELECT * FROM users WHERE id = @userId");
return byId.get({ userId });
};
router.get("/", (_req, res) => {
const listUsers = db.prepare(`SELECT * FROM users`);
const users = listUsers.all();
res.json(users);
});
router.post("/new", (req, res) => {
const data = req.body;
const cols = Object.keys(data).join(" , ");
const vals = Object.values(data).join(" , ");
const insertUser = db.prepare(`INSERT INTO users(@cols) VALUES (@vals)`);
const { lastInsertRowid } = insertUser.run({ cols, vals });
const id = lastInsertRowid as number;
const user = getUser(id);
res.json(user);
});
router.get("/:id", (req, res) => {
const id = Number(req.params.id);
const user = getUser(id);
if (!user) {
res.status(404).json({ error: "User not found" });
}
res.json(user);
});
router.patch("/:id", (req, res) => {
const userId = Number(req.params.id);
const patch = req.body;
const updateCol = db.prepare(`
UPDATE users SET @col = @val WHERE id = @userId
`);
const updateUser = db.transaction((patch) => {
for (const [col, val] of Object.entries(patch)) {
updateCol.run(col, val, userId);
}
});
updateUser(Object.entries(patch));
const updated = getUser(userId);
res.json(updated);
});
router.delete("/:id", (req, res) => {
const deleteUser = db.prepare(`DELETE FROM users WHERE id = @userId`);
const userId = parseInt(req.params.id);
const user = getUser(userId);
if (!user) {
res.status(404).json({ error: "User not found" });
}
deleteUser.run({ userId });
res.json(user);
});
export default router;
|