summaryrefslogtreecommitdiff
path: root/backend/src/routes/users.js
diff options
context:
space:
mode:
authorAnjana Vakil <contact@anjana.dev>2025-08-26 12:40:16 -0500
committerAnjana Vakil <contact@anjana.dev>2025-08-26 12:40:16 -0500
commit1dc4f56425209d4ce1d7bb78ec8b5e7b5a755a82 (patch)
tree58d06cd695ae17302daff7a87d9096f1d39ea54a /backend/src/routes/users.js
reset
Diffstat (limited to 'backend/src/routes/users.js')
-rw-r--r--backend/src/routes/users.js65
1 files changed, 65 insertions, 0 deletions
diff --git a/backend/src/routes/users.js b/backend/src/routes/users.js
new file mode 100644
index 0000000..6d874e9
--- /dev/null
+++ b/backend/src/routes/users.js
@@ -0,0 +1,65 @@
+import { Router } from 'express';
+import db from '../db.js';
+
+const router = Router();
+
+export const getUser = (userId) => {
+ 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: id } = insertUser.run({ cols, vals });
+ const user = getUser(id);
+ res.json(user);
+});
+
+router.get('/:id', (req, res) => {
+ const id = 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 = 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;