diff options
| author | Leo Goetz <dev@leogtz.de> | 2026-01-22 09:10:15 +0100 |
|---|---|---|
| committer | Leo Goetz <dev@leogtz.de> | 2026-01-22 09:10:15 +0100 |
| commit | 01c0f792484f8f52606eae0e58abe528acef3086 (patch) | |
| tree | e30894caf65b39aab1e050035f63450b5032123c /backend/src/routes/users.ts | |
| parent | b6d422d33c3b647ab249a8cf3520bc986fa2c549 (diff) | |
Diffstat (limited to 'backend/src/routes/users.ts')
| -rw-r--r-- | backend/src/routes/users.ts | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/backend/src/routes/users.ts b/backend/src/routes/users.ts new file mode 100644 index 0000000..98ec361 --- /dev/null +++ b/backend/src/routes/users.ts @@ -0,0 +1,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; |
