Files
bini-google-tv/backend/routes/todos.js

107 lines
2.8 KiB
JavaScript

const express = require("express");
const Todo = require("../models/Todo");
const router = express.Router();
// Get day range in Korea Standard Time (UTC+9)
const getDayRange = () => {
const now = new Date();
// Get current time in KST (UTC+9)
const kstOffset = 9 * 60; // minutes
const utcTime = now.getTime() + (now.getTimezoneOffset() * 60000);
const kstTime = new Date(utcTime + (kstOffset * 60000));
// Start of day in KST
const startKst = new Date(kstTime);
startKst.setHours(0, 0, 0, 0);
// End of day in KST
const endKst = new Date(kstTime);
endKst.setHours(23, 59, 59, 999);
// Convert back to UTC for MongoDB query
const start = new Date(startKst.getTime() - (kstOffset * 60000));
const end = new Date(endKst.getTime() - (kstOffset * 60000));
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 } = getDayRange();
// Show incomplete todos that are:
// 1. Due today or later (not overdue)
// 2. Have no due date set
const todos = await Todo.find({
completed: false,
$or: [
{ dueDate: { $gte: start } },
{ dueDate: { $exists: false } },
{ dueDate: null }
]
}).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;