Initial commit
This commit is contained in:
81
backend/routes/todos.js
Normal file
81
backend/routes/todos.js
Normal file
@@ -0,0 +1,81 @@
|
||||
const express = require("express");
|
||||
const Todo = require("../models/Todo");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const getDayRange = (date = new Date()) => {
|
||||
const start = new Date(date);
|
||||
start.setHours(0, 0, 0, 0);
|
||||
const end = new Date(date);
|
||||
end.setHours(23, 59, 59, 999);
|
||||
return { start, end };
|
||||
};
|
||||
|
||||
router.get("/", async (req, res) => {
|
||||
try {
|
||||
const todos = await Todo.find().sort({ dueDate: 1, createdAt: -1 });
|
||||
res.json(todos);
|
||||
} catch (error) {
|
||||
res.status(500).json({ message: "Failed to fetch todos" });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/today", async (req, res) => {
|
||||
try {
|
||||
const { start, end } = getDayRange();
|
||||
const todos = await Todo.find({ dueDate: { $gte: start, $lte: end } }).sort({
|
||||
dueDate: 1,
|
||||
createdAt: -1,
|
||||
});
|
||||
res.json(todos);
|
||||
} catch (error) {
|
||||
res.status(500).json({ message: "Failed to fetch today todos" });
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/", async (req, res) => {
|
||||
try {
|
||||
const todo = await Todo.create(req.body);
|
||||
res.status(201).json(todo);
|
||||
} catch (error) {
|
||||
res.status(400).json({ message: "Failed to create todo" });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/:id", async (req, res) => {
|
||||
try {
|
||||
const todo = await Todo.findById(req.params.id);
|
||||
if (!todo) {
|
||||
return res.status(404).json({ message: "Todo not found" });
|
||||
}
|
||||
res.json(todo);
|
||||
} catch (error) {
|
||||
res.status(400).json({ message: "Failed to fetch todo" });
|
||||
}
|
||||
});
|
||||
|
||||
router.put("/:id", async (req, res) => {
|
||||
try {
|
||||
const todo = await Todo.findByIdAndUpdate(req.params.id, req.body, { new: true });
|
||||
if (!todo) {
|
||||
return res.status(404).json({ message: "Todo not found" });
|
||||
}
|
||||
res.json(todo);
|
||||
} catch (error) {
|
||||
res.status(400).json({ message: "Failed to update todo" });
|
||||
}
|
||||
});
|
||||
|
||||
router.delete("/:id", async (req, res) => {
|
||||
try {
|
||||
const todo = await Todo.findByIdAndDelete(req.params.id);
|
||||
if (!todo) {
|
||||
return res.status(404).json({ message: "Todo not found" });
|
||||
}
|
||||
res.json({ ok: true });
|
||||
} catch (error) {
|
||||
res.status(400).json({ message: "Failed to delete todo" });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
Reference in New Issue
Block a user