-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
92 lines (76 loc) · 2.48 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
const PORT = 8000;
app.use(cors());
app.use(express.json());
mongoose.connect('mongodb://localhost:27017/calendar-todo', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const todoSchema = new mongoose.Schema({
text: { type: String, required: true },
priority: { type: String, default: 'Low' },
date: { type: Date, default: Date.now },
category: { type: String, default: 'General' },
isDone: { type: Boolean, default: false }, // New field for tracking done status
});
const Todo = mongoose.model('Todo', todoSchema);
// New route to toggle the "isDone" property
app.patch('/api/todo/:id', async (req, res) => {
try {
const todoId = req.params.id;
const updatedTodo = await Todo.findByIdAndUpdate(
todoId,
{ isDone: !req.body.isDone }, // Toggle the "isDone" property
{ new: true }
);
if (!updatedTodo) {
return res.status(404).json({ error: 'Todo not found' });
}
res.json(updatedTodo);
} catch (error) {
console.error('Error updating todo:', error);
res.status(500).json({ error: 'Server error' });
}
});
app.delete('/api/todo/:id', async (req, res) => {
try {
const deletedTodo = await Todo.findByIdAndDelete(req.params.id);
if (!deletedTodo) {
return res.status(404).json({ error: 'Todo not found' });
}
res.json(deletedTodo);
} catch (error) {
console.error('Error deleting todo:', error);
res.status(500).json({ error: 'Server error' });
}
});
app.get('/api/todo', async (req, res) => {
try {
const todos = await Todo.find().sort({ date: -1 });
res.json(todos);
} catch (error) {
console.error('Error fetching todos:', error);
res.status(500).json({ error: 'Server error' });
}
});
app.post('/api/todo', async (req, res) => {
try {
const { text, priority = 'Low', category = 'General' } = req.body;
// Use findOneAndUpdate to either update an existing todo or create a new one
const updatedTodo = await Todo.findOneAndUpdate(
{ text, category },
{ text, priority, category, date: Date.now() },
{ upsert: true, new: true, setDefaultsOnInsert: true }
);
res.json(updatedTodo);
} catch (error) {
console.error('Error adding/updating todo:', error);
res.status(500).json({ error: 'Server error' });
}
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});