aboutsummaryrefslogtreecommitdiffstats
path: root/routes/tasks.js
diff options
context:
space:
mode:
Diffstat (limited to 'routes/tasks.js')
-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;