Untitled

 avatar
unknown
plain_text
2 months ago
2.2 kB
1
Indexable
const express = require('express');
const bodyParser = require('body-parser');

const app = express();

// Middleware to parse JSON bodies
app.use(bodyParser.json());

// In-memory task storage (we will use an array to store tasks temporarily)
let tasks = [];

// Create a new task
app.post('/tasks', (req, res) => {
    const { title, description, dueDate } = req.body;

    // Validate input fields
    if (!title || !description) {
        return res.status(400).json({ message: 'Title and description are required' });
    }

    // Create a new task
    const newTask = {
        id: tasks.length + 1,
        title,
        description,
        dueDate,
        completed: false,
    };

    // Store the new task
    tasks.push(newTask);

    // Respond with the created task
    res.status(201).json(newTask);
});

// Get all tasks
app.get('/tasks', (req, res) => {
    res.json(tasks);
});

// Update a task
app.put('/tasks/:id', (req, res) => {
    const taskId = parseInt(req.params.id);
    const task = tasks.find(t => t.id === taskId);

    // Check if the task exists
    if (!task) {
        return res.status(404).json({ message: 'Task not found' });
    }

    const { title, description, dueDate, completed } = req.body;

    // Update task fields
    if (title) task.title = title;
    if (description) task.description = description;
    if (dueDate) task.dueDate = dueDate;
    if (completed !== undefined) task.completed = completed;

    // Respond with the updated task
    res.json(task);
});

// Delete a task
app.delete('/tasks/:id', (req, res) => {
    const taskId = parseInt(req.params.id);
    const taskIndex = tasks.findIndex(t => t.id === taskId);

    // Check if the task exists
    if (taskIndex === -1) {
        return res.status(404).json({ message: 'Task not found' });
    }

    // Remove the task from the array
    tasks.splice(taskIndex, 1);

    // Respond with no content status (204)
    res.status(204).send();
});

// Start the server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});
Editor is loading...
Leave a Comment