-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
66 lines (57 loc) · 1.6 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
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();
const port = process.env.PORT || 3000;
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static('.'));
// In-memory todos array
let todos = [];
// Get all todos
app.get('/api/todos', (req, res) => {
res.json(todos);
});
// Add a new todo
app.post('/api/todos', (req, res) => {
const todo = {
id: Date.now(),
text: req.body.text,
completed: false
};
todos.push(todo);
res.status(201).json(todo);
});
// Toggle todo completion
app.put('/api/todos/:id', (req, res) => {
const id = parseInt(req.params.id);
todos = todos.map(todo =>
todo.id === id ? { ...todo, completed: !todo.completed } : todo
);
const updatedTodo = todos.find(todo => todo.id === id);
if (updatedTodo) {
res.json(updatedTodo);
} else {
res.status(404).json({ error: 'Todo not found' });
}
});
// Delete a todo
app.delete('/api/todos/:id', (req, res) => {
const id = parseInt(req.params.id);
const initialLength = todos.length;
todos = todos.filter(todo => todo.id !== id);
if (todos.length < initialLength) {
res.status(204).send();
} else {
res.status(404).json({ error: 'Todo not found' });
}
});
// Only start the server if this file is run directly
if (require.main === module) {
const server = app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
console.log(`Environment: ${process.env.NODE_ENV}`);
});
}
module.exports = app;