aboutsummaryrefslogtreecommitdiffstats
path: root/routes/tasks.js
diff options
context:
space:
mode:
authorpack <pack@packgekko.xyz>2026-08-12 17:06:50 +0000
committerpack <pack@packgekko.xyz>2026-08-12 17:06:50 +0000
commit5611527e313c4add16c432e5cf9d55a987558c02 (patch)
tree59ad054325096b6305277b94982bbe7f7f585f59 /routes/tasks.js
parentd3adc16a08d95d6e331de55d7d3bf05a66a874a8 (diff)
downloadcrud-5611527e313c4add16c432e5cf9d55a987558c02.tar.gz
final commit
Diffstat (limited to '')
-rw-r--r--routes/tasks.js54
1 files changed, 54 insertions, 0 deletions
diff --git a/routes/tasks.js b/routes/tasks.js
index e69de29..99b1748 100644
--- a/routes/tasks.js
+++ b/routes/tasks.js
@@ -0,0 +1,54 @@
+const express = require('express');
+const db = require('../db');
+const auth = require('../middleware/auth');
+const router = express.Router();
+
+/* all routes require login. */
+router.use(auth);
+
+/* create. */
+router.post('/', (req, res) =>
+{
+ const { title, description } = req.body;
+ if (!title) return res.status(400).json({ error: 'Title required' });
+ const result = db.prepare(
+ 'INSERT INTO tasks (user_id, title, description) VALUES (?, ?, ?)'
+ ).run(req.session.userId, title, description || '');
+ res.json({ id: result.lastInsertRowid, title, description: description || '', done: 0 });
+});
+
+/* read all. */
+router.get('/', (req, res) =>
+{
+ const rows = db.prepare('SELECT * FROM tasks WHERE user_id = ?').all(req.session.userId);
+ res.json(rows);
+});
+
+/* read on. */
+router.get('/:id', (req, res) =>
+{
+ const row = db.prepare('SELECT * FROM tasks WHERE id = ? AND user_id = ?').get(req.params.id, req.session.userId);
+ if (!row) return res.status(404).json({ error: 'Task not found' });
+ res.json(row);
+});
+
+/* update. */
+router.put('/:id', (req, res) =>
+{
+ const { title, description, done } = req.body;
+ const result = db.prepare(
+ 'UPDATE tasks SET title = COALESCE(?, title), description = COALESCE(?, description), done = COALESCE(?, done) WHERE id = ? AND user_id = ?'
+ ).run(title, description, done, req.params.id, req.session.userId);
+ if (result.changes === 0) return res.status(404).json({ error: 'Task not found' });
+ res.json({ id: Number(req.params.id), title, description, done });
+});
+
+/* delete. */
+router.delete('/:id', (req, res) =>
+{
+ const result = db.prepare('DELETE FROM tasks WHERE id = ? AND user_id = ?').run(req.params.id, req.session.userId);
+ if (result.changes === 0) return res.status(404).json({ error: 'Task not found' });
+ res.json({ message: 'Deleted' });
+});
+
+module.exports = router;