110 lines
3.6 KiB
JavaScript
110 lines
3.6 KiB
JavaScript
// routes/todoRoutes.js
|
|
// Handles CRUD operations for todo items for the logged-in user
|
|
|
|
const express = require('express');
|
|
const db = require('../db');
|
|
const authenticateToken = require('../middleware/authMiddleware'); // Import auth middleware
|
|
|
|
const router = express.Router();
|
|
|
|
// All routes in this file require authentication
|
|
router.use(authenticateToken);
|
|
|
|
// GET /api/todos - Get all todos for the logged-in user
|
|
router.get('/', async (req, res) => {
|
|
const userId = req.user.id; // Get user ID from the authenticated token payload
|
|
|
|
try {
|
|
const result = await db.query(
|
|
'SELECT id, task, is_completed FROM todos WHERE user_id = $1 ORDER BY created_at DESC',
|
|
[userId]
|
|
);
|
|
res.status(200).json(result.rows);
|
|
} catch (error) {
|
|
console.error('Error fetching todos:', error);
|
|
res.status(500).json({ message: 'Fehler beim Abrufen der Todos.' });
|
|
}
|
|
});
|
|
|
|
// POST /api/todos - Create a new todo for the logged-in user
|
|
router.post('/newEntry', async (req, res) => {
|
|
const userId = req.user.id;
|
|
const { task } = req.body;
|
|
|
|
console.log('Received task:', task); // Log the received task for debugging
|
|
if (!task || task.trim() === '') {
|
|
return res.status(400).json({ message: 'Aufgabeninhalt darf nicht leer sein.' });
|
|
}
|
|
|
|
try {
|
|
const result = await db.query(
|
|
'INSERT INTO todos (user_id, task) VALUES ($1, $2) RETURNING id, task, is_completed',
|
|
[userId, task.trim()]
|
|
);
|
|
res.status(201).json(result.rows[0]); // Return the newly created todo
|
|
} catch (error) {
|
|
console.error('Error creating todo:', error);
|
|
res.status(500).json({ message: 'Fehler beim Erstellen des Todos.' });
|
|
}
|
|
});
|
|
|
|
// PUT /api/todos/:id - Update a todo's completion status
|
|
router.put('/:id', async (req, res) => {
|
|
const userId = req.user.id;
|
|
const todoId = parseInt(req.params.id, 10);
|
|
const { is_completed } = req.body; // Expecting { is_completed: true/false }
|
|
|
|
if (isNaN(todoId)) {
|
|
return res.status(400).json({ message: 'Ungültige Todo ID.' });
|
|
}
|
|
if (typeof is_completed !== 'boolean') {
|
|
return res.status(400).json({ message: 'Ungültiger Statuswert.' });
|
|
}
|
|
|
|
try {
|
|
const result = await db.query(
|
|
'UPDATE todos SET is_completed = $1 WHERE id = $2 AND user_id = $3 RETURNING id, task, is_completed',
|
|
[is_completed, todoId, userId]
|
|
);
|
|
|
|
if (result.rows.length === 0) {
|
|
// Either todo doesn't exist or doesn't belong to the user
|
|
return res.status(404).json({ message: 'Todo nicht gefunden oder Zugriff verweigert.' });
|
|
}
|
|
|
|
res.status(200).json(result.rows[0]); // Return the updated todo
|
|
} catch (error) {
|
|
console.error('Error updating todo:', error);
|
|
res.status(500).json({ message: 'Fehler beim Aktualisieren des Todos.' });
|
|
}
|
|
});
|
|
|
|
// DELETE /api/todos/:id - Delete a todo
|
|
router.delete('/:id', async (req, res) => {
|
|
const userId = req.user.id;
|
|
const todoId = parseInt(req.params.id, 10);
|
|
|
|
if (isNaN(todoId)) {
|
|
return res.status(400).json({ message: 'Ungültige Todo ID.' });
|
|
}
|
|
|
|
try {
|
|
const result = await db.query(
|
|
'DELETE FROM todos WHERE id = $1 AND user_id = $2 RETURNING id',
|
|
[todoId, userId]
|
|
);
|
|
|
|
if (result.rowCount === 0) {
|
|
// Either todo doesn't exist or doesn't belong to the user
|
|
return res.status(404).json({ message: 'Todo nicht gefunden oder Zugriff verweigert.' });
|
|
}
|
|
|
|
res.status(200).json({ message: 'Todo erfolgreich gelöscht.' }); // Or use 204 No Content
|
|
} catch (error) {
|
|
console.error('Error deleting todo:', error);
|
|
res.status(500).json({ message: 'Fehler beim Löschen des Todos.' });
|
|
}
|
|
});
|
|
|
|
module.exports = router;
|