-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
239 lines (197 loc) · 5.91 KB
/
server.js
File metadata and controls
239 lines (197 loc) · 5.91 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
const express = require('express');
const cors = require('cors');
const Database = require('better-sqlite3');
const app = express();
app.use(cors());
app.use(express.json());
// Initialize database
const db = new Database('tasks.db');
// Create table if not exists
db.exec(`
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
description TEXT,
status TEXT DEFAULT 'pending',
due_date TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP
)
`);
// Middleware to update timestamp
app.use((req, res, next) => {
if (['POST', 'PUT', 'PATCH'].includes(req.method)) {
req.body.updated_at = new Date().toISOString();
}
next();
});
// Helper function
const getTask = (id) => {
const task = db.prepare('SELECT * FROM tasks WHERE id = ?').get(id);
return task;
};
// GET /api/tasks - List all tasks
app.get('/api/tasks', (req, res) => {
try {
const { status, limit = 50, offset = 0 } = req.query;
let query = 'SELECT * FROM tasks WHERE 1=1';
const params = [];
if (status) {
query += ' AND status = ?';
params.push(status);
}
query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
params.push(parseInt(limit), parseInt(offset));
const tasks = db.prepare(query).all(...params);
res.json(tasks);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// GET /api/tasks/:id - Get a single task
app.get('/api/tasks/:id', (req, res) => {
try {
const task = getTask(req.params.id);
if (!task) {
return res.status(404).json({ error: 'Task not found' });
}
res.json(task);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// POST /api/tasks - Create a new task
app.post('/api/tasks', (req, res) => {
try {
const { title, description, status = 'pending', due_date } = req.body;
if (!title) {
return res.status(400).json({ error: 'Title is required' });
}
const validStatuses = ['pending', 'in_progress', 'completed'];
if (!validStatuses.includes(status)) {
return res.status(400).json({ error: 'Invalid status' });
}
const result = db.prepare(`
INSERT INTO tasks (title, description, status, due_date)
VALUES (?, ?, ?, ?)
`).run(title, description, status, due_date || null);
const task = getTask(result.lastInsertRowid);
res.status(201).json(task);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// PUT /api/tasks/:id - Update a task
app.put('/api/tasks/:id', (req, res) => {
try {
const { title, description, status, due_date } = req.body;
const existingTask = getTask(req.params.id);
if (!existingTask) {
return res.status(404).json({ error: 'Task not found' });
}
const updates = [];
const values = [];
if (title !== undefined) {
updates.push('title = ?');
values.push(title);
}
if (description !== undefined) {
updates.push('description = ?');
values.push(description);
}
if (status !== undefined) {
const validStatuses = ['pending', 'in_progress', 'completed'];
if (!validStatuses.includes(status)) {
return res.status(400).json({ error: 'Invalid status' });
}
updates.push('status = ?');
values.push(status);
}
if (due_date !== undefined) {
updates.push('due_date = ?');
values.push(due_date || null);
}
if (updates.length === 0) {
return res.status(400).json({ error: 'No fields to update' });
}
updates.push('updated_at = CURRENT_TIMESTAMP');
values.push(req.params.id);
db.prepare(`
UPDATE tasks SET ${updates.join(', ')}
WHERE id = ?
`).run(...values);
const task = getTask(req.params.id);
res.json(task);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// PATCH /api/tasks/:id/status - Update task status
app.patch('/api/tasks/:id/status', (req, res) => {
try {
const { status } = req.body;
const validStatuses = ['pending', 'in_progress', 'completed'];
if (!validStatuses.includes(status)) {
return res.status(400).json({ error: 'Invalid status' });
}
const existingTask = getTask(req.params.id);
if (!existingTask) {
return res.status(404).json({ error: 'Task not found' });
}
db.prepare(`
UPDATE tasks
SET status = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = ?
`).run(status, req.params.id);
const task = getTask(req.params.id);
res.json(task);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// DELETE /api/tasks/:id - Delete a task
app.delete('/api/tasks/:id', (req, res) => {
try {
const existingTask = getTask(req.params.id);
if (!existingTask) {
return res.status(404).json({ error: 'Task not found' });
}
db.prepare('DELETE FROM tasks WHERE id = ?').run(req.params.id);
res.json({ message: 'Task deleted successfully' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// GET /api/tasks/stats - Get task statistics
app.get('/api/tasks/stats', (req, res) => {
try {
const stats = db.prepare(`
SELECT
status,
COUNT(*) as count
FROM tasks
GROUP BY status
`).all();
const result = {
pending: 0,
in_progress: 0,
completed: 0
};
stats.forEach(stat => {
result[stat.status] = stat.count;
});
result.total = Object.values(result).reduce((a, b) => a + b, 0);
res.json(result);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Task API server running on port ${PORT}`);
});
// Graceful shutdown
process.on('SIGINT', () => {
db.close();
process.exit(0);
});