Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions backend/controllers/todos.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// stored here
let list = [
{
id: 1,
title: "Testing1",
completed: false,
createdAt: Date.now(),
},
];

// all todo
const getTodos = (req, res) => {
res.status(200).json(list);
};

// get a todo by id
const getTodo = (req, res) => {

const id = Number(req.params.id);
const todo = list.find((list) => list.id === id);

if (!todo) {
return res.status(400).json({ message: "Todo not found" });
}
res.status(200).json(todo);
}


// new todo
const createTodos = (req, res) => {
if (!req.body.title) {
return res.status(400).json({ message: "Title required" });
}
const newTodo = {
id: list.length + 1,
title: req.body.title,
completed: false,
createdAt: Date.now(),
};
list.push(newTodo);
res.status(201).json(newTodo);
};

// update
const updateTodo = (req, res) => {
const id = Number(req.params.id);
const todo = list.find((list) => list.id === id);
if (!todo) {
return res.status(404).json({ message: "Cannot find a ToDo list" });
}
if (req.body.title !== undefined) {
todo.title = req.body.title;
}

if (req.body.completed !== undefined) {
todo.completed = req.body.completed;
}
res.status(200).json(todo);
};

// delete
const deleteTodo = (req, res) => {
const id = Number(req.params.id);
const index = list.findIndex(list => list.id === id);

if (index === -1) {
return res.status(404).json({ message: "Todo not found" });
}

const deleted = list.splice(index, 1)[0];

res.status(200).json(deleted);
};

module.exports = { getTodos, getTodo, createTodos, updateTodo, deleteTodo };
22 changes: 19 additions & 3 deletions backend/index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,29 @@
const express = require("express");
const app = express();
const PORT = process.env.PORT || 4000;
const router = express.Router();
const { getTodos , getTodo, createTodos , updateTodo, deleteTodo } = require("./controllers/todos.controller.js");

// for middleware
app.use(express.json());

app.use('/api/todos', router);

// routes
router.get("/", getTodos);
router.get("/:id", getTodo);
router.post("/", createTodos);
router.put("/:id", updateTodo);
router.delete("/:id", deleteTodo);

// Basic route
app.get("/", (req, res) => {
res.send("Hello from Express!");
});
/* app.get("/", (req, res) => {
res.send("Hello from Express js!");
}); */

// Start server
app.listen(PORT, () => {
console.log(`Backend is running on http://localhost:${PORT}`);
});

module.exports = router;
Loading