From 9b0197585fd7742f3245f94ddbd9f5b12e3ebd3d Mon Sep 17 00:00:00 2001 From: Jesus Galaz <jesusgalazr@icloud.com> Date: Sun, 6 Oct 2024 17:21:48 +0200 Subject: [PATCH] Adding server.js functionality and main operations for todos.js --- routes/todos.js | 33 +++++++++++++++++++++++++++++++++ server.js | 22 +++++++++++++++------- 2 files changed, 48 insertions(+), 7 deletions(-) diff --git a/routes/todos.js b/routes/todos.js index e69de29..49a3ea1 100644 --- a/routes/todos.js +++ b/routes/todos.js @@ -0,0 +1,33 @@ +const express = require('express'); +const router = express.Router(); +const Todo = require('../models/todo'); + +// Get all TODOs for the logged-in user +router.get('/', async (req, res) => { + const todos = await Todo.find({ userId: req.user.id }); + res.json(todos); +}); + +// Add a new TODO +router.post('/', async (req, res) => { + const { description } = req.body; + const todo = new Todo({ description, userId: req.user.id }); + await todo.save(); + res.json(todo); +}); + +// Mark TODO as done +router.put('/:id', async (req, res) => { + const todo = await Todo.findById(req.params.id); + todo.isDone = true; + await todo.save(); + res.json(todo); +}); + +// Delete a TODO +router.delete('/:id', async (req, res) => { + await Todo.findByIdAndDelete(req.params.id); + res.json({ success: true }); +}); + +module.exports = router; diff --git a/server.js b/server.js index e251644..a48072d 100644 --- a/server.js +++ b/server.js @@ -1,13 +1,21 @@ +// server.js const express = require('express'); +const path = require('path'); +const connectDB = require('./mongodb'); // Import the MongoDB connection + const app = express(); -// Basic route for testing -app.get('/', (req, res) => { - res.send('Server is running!'); -}); +// Middleware +app.use(express.json()); // Use express' built-in body-parser for JSON +app.use(express.static(path.join(__dirname, 'public'))); // Serve static files + +// Connect to MongoDB +connectDB(); // Call the function to establish the database connection + +// Routes +app.use('/api/todos', require('./routes/todos')); +app.use('/api/users', require('./routes/users')); // Start the server const PORT = process.env.PORT || 3000; -app.listen(PORT, () => { - console.log(`Server is running on port ${PORT}`); -}); +app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); -- GitLab