more changes

This commit is contained in:
2026-04-21 15:44:34 +08:00
parent 2a7eea5733
commit a49eb4e77c
3 changed files with 147 additions and 68 deletions

View File

@@ -1,2 +1,3 @@
PORT = 3001 PORT = 3001
MONGO_URI = "mongodb+srv://timmybee:EMqczsTr1oYPBtCd@cluster0.dombm2a.mongodb.net/?appName=Cluster0" MONGO_URI = "mongodb+srv://timmybee:EMqczsTr1oYPBt@cluster0.dombm2a.mongodb.net/?appName=Cluster0"
APP_URI = "http://localhost:3001"

View File

@@ -7,84 +7,161 @@ const port = 3001;
const app = express(); const app = express();
app.use(express.json()); app.use(express.json());
app.use(cors());
app.use(cors("*")); (async () => {
// app.get("/test", async (req, res) => {
// res.send("Hello World!");
// });
const tasks = [
{
id: 1,
completed: false,
title: "Buy groceries for the week",
description: "Pick up vegetables, fruits, milk, eggs, and bread from the supermarket.",
dueDate: "14/03/2026",
dateCreated: new Date(Date.now()).toLocaleDateString("en-AU")
},
{
id: 2,
completed: false,
title: "Clean the apartment",
description: "Vacuum the floors, wipe kitchen surfaces, and take out the trash.",
dueDate: "16/03/2026",
dateCreated: new Date(Date.now()).toLocaleDateString("en-AU")
},
{
id: 3,
completed: false,
title: "Call the dentist for appointment",
description: "Book a routine checkup and confirm available time slots for next week.",
dueDate: "17/03/2026",
dateCreated: new Date(Date.now()).toLocaleDateString("en-AU")
},
{
id: 4,
completed: true,
title: "Do laundry and fold clothes",
description: "Wash dark and light loads separately, then fold and organize clean clothes.",
dueDate: "21/03/2026",
dateCreated: new Date(Date.now()).toLocaleDateString("en-AU")
}
];
app.get("/api/tasks", async (req, res) => {
try { try {
res.json(tasks); mongoose.set("autoIndex", false);
}
catch (error) {
console.error(`Error: ${error}`)
res.status(500).json({ message: "Error getting tasks" })
}
});
app.post("/api/tasks/todo", async (req, res) => { await mongoose.connect(process.env.MONGO_URI);
try { console.log("✅ MongoDB Connected");
const { title, description, dueDate } = req.body;
const newTask = { await Task.syncIndexes();
id: tasks.length + 1, console.log("✅ Indexes created");
completed: false,
title, title,
description, description,
dueDate, dueDate,
dateCreated: new Date(Date.now()).toLocaleDateString("en-AU"),
};
tasks.push(newTask);
res.json(newTask);
res.status(201).json(newTask);
}
catch (error) {
console.error(`Error: ${error}`)
res.status(500).json({ message: "Error creating task" })
}
});
app.listen(port, () => { app.listen(port, () => {
console.log(`To Do App listening on port ${port}`); console.log(`To Do App listening on port ${port}`);
});
} catch (error) {
console.error(`Startup Error! ${error}`);
}
})();
// Task Schema
const taskSchema = new mongoose.Schema({
title: { type: String, required: true },
completed: { type: Boolean, required: true, default: false },
description: { type: String, required: true },
dueDate: { type: Date, required: true },
dateCreated: { type: Date, required: true, default: new Date() }
})
taskSchema.index({ dueDate: 1 })
taskSchema.index({ dateCreated: 1 })
const Task = mongoose.model("Task", taskSchema);
app.get('/api/tasks', async (req, res) => {
try {
const { sortBy } = req.query; // ?sortBy=dueDate or ?sortBy=dateCreated
let sortOption = {};
if (sortBy === 'dueDate') {
sortOption = { dueDate: 1 }; // Ascending
} else if (sortBy === 'dateCreated') {
sortOption = { dateCreated: 1 };
}
const tasks = await Task.find({}).sort(sortOption);
if (!tasks) {
return res.status(404).json({ message: "Tasks not found!" });
}
res.json(tasks);
} catch (error) {
console.error("Error:", error);
res.status(500).json({ message: "Error grabbing tasks!" });
}
});
app.post('/api/tasks/todo', async (req, res) => {
try {
const { title, description, dueDate } = req.body;
const taskData = { title, description, dueDate };
const createTask = new Task(taskData);
const newTask = await createTask.save();
res.json({ task: newTask, message: "New task created successfully!" });
} catch (error) {
console.error("Error:", error);
res.status(500).json({ message: "Error creating the task!" });
}
});
// To 'complete' the task and move columns ↓
app.patch('/api/tasks/complete/:id', async (req, res) => {
try {
const { completed } = req.body;
const taskId = req.params.id;
const completedTask = await Task.findByIdAndUpdate(taskId, { completed }, { new: true });
if (!completedTask) {
return res.status(404).json({ message: "Task not found!" });
}
res.json({ task: completedTask, message: "Task set to 'Complete'" });
} catch (error) {
console.error("Error:", error);
res.status(500).json({ message: "Error completing the task!" });
}
});
// To make the task 'not complete' and move columns ↓
app.patch('/api/tasks/notComplete/:id', async (req, res) => {
try {
const { completed } = req.body;
const taskId = req.params.id;
const taskNotComplete = await Task.findByIdAndUpdate(taskId, { completed }, { new: true });
if (!taskNotComplete) {
return res.status(404).json({ message: "Task not found!" });
}
res.json({ task: taskNotComplete, message: "Task set to 'Not Complete'" });
} catch (error) {
console.error("Error:", error);
res.status(500).json({ message: "Error making the task NOT complete!" });
}
});
app.delete('/api/tasks/delete/:id', async (req, res) => {
try {
const taskId = req.params.id;
const deletedTask = await Task.findByIdAndDelete(taskId);
if (!deletedTask) {
return res.status(404).json({ message: "Task not found!" });
}
res.json({ task: deletedTask, message: "Task deleted successfully!" });
} catch (error) {
console.error("Error:", error);
res.status(500).json({ message: "Error deleting the task!" });
}
});
// To edit exisiting task and update
app.put('/api/tasks/update/:id', async (req, res) => {
try {
const taskId = req.params.id;
const { title, description, dueDate } = req.body; // Extract data from front end request
const taskData = { title, description, dueDate };
const updatedTask = await Task.findByIdAndUpdate(taskId, taskData, { new: true });
if (!updatedTask) {
return res.status(404).json({ message: "Task not found!" });
}
res.json({ task: updatedTask, message: "Task updated successfully!" });
} catch (error) {
console.error('Error:', error);
res.status(500).json({ message: "Error updating the task!" });
}
}); });

View File

@@ -4,6 +4,7 @@
"description": "", "description": "",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1"
}, },
"keywords": [], "keywords": [],