-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
169 lines (159 loc) · 4.55 KB
/
Copy pathserver.js
File metadata and controls
169 lines (159 loc) · 4.55 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
import express from 'express';
import {
createTask,
deleteTask,
getAllTasks,
getTaskById,
updateTask,
} from './src/data-access/taskRepository.js';
import { Task } from './src/models/Task.js';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
function isValidIsoDate(dateString) {
if (typeof dateString !== 'string') {
return false;
}
const isoDatePattern = /^\d{4}-\d{2}-\d{2}$/; // regex to check for YYYY-MM-DD format
if (!isoDatePattern.test(dateString)) {
return false;
}
const date = new Date(dateString);
return (
!Number.isNaN(date.getTime()) &&
date.toISOString().slice(0, 10) === dateString
);
}
function validateOptionalIsoDate(value, fieldName, res) {
if (value !== undefined && value !== null && !isValidIsoDate(value)) {
res
.status(400)
.json({ error: `${fieldName} must be in YYYY-MM-DD format` });
return false;
}
return true;
}
export function createApp() {
const app = express();
// Keep JSON middleware for API requests.
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
// Frontend hook: replace this JSON response with res.sendFile(...) for index.html.
res.json({ message: 'Task API is running' });
});
app.get('/tasks', (req, res) => {
try {
const tasks = getAllTasks();
res.json({ tasks });
} catch {
res.status(500).json({ error: 'Failed to read tasks data' });
}
});
app.get('/tasks/:id', (req, res) => {
try {
const id = Number.parseInt(req.params.id, 10);
if (Number.isNaN(id)) {
return res.status(400).json({ error: 'Invalid task id' });
}
const task = getTaskById(id);
if (!task) {
return res.status(404).json({ error: 'Task not found' });
}
res.json({ task });
} catch {
res.status(500).json({ error: 'Failed to read task' });
}
});
app.post('/tasks', (req, res) => {
try {
const {
name,
description,
category,
importance,
status,
date_finished,
deadline,
} = req.body;
const candidateTask = new Task({
name,
description,
category,
importance,
status,
date_finished,
deadline,
});
candidateTask.validate();
if (!validateOptionalIsoDate(deadline, 'deadline', res)) {
return;
}
if (!validateOptionalIsoDate(date_finished, 'date_finished', res)) {
return;
}
const newTask = createTask({
name,
description: description ?? '',
category,
importance,
status,
date_finished: date_finished ?? null,
deadline: deadline ?? null,
});
return res.status(201).json({ task: newTask });
} catch (error) {
console.error('Failed to read tasks data:', error);
return res
.status(400)
.json({ error: error.message || 'Failed to create task' });
}
});
app.put('/tasks/:id', (req, res) => {
try {
const { deadline, date_finished } = req.body;
const id = Number.parseInt(req.params.id, 10);
if (Number.isNaN(id)) {
return res.status(400).json({ error: 'Invalid task id' });
}
const existingTask = getTaskById(id);
if (!existingTask) {
return res.status(404).json({ error: 'Task not found' });
}
if (!validateOptionalIsoDate(deadline, 'deadline', res)) {
return;
}
if (!validateOptionalIsoDate(date_finished, 'date_finished', res)) {
return;
}
const candidateTask = new Task({
...existingTask,
...req.body,
});
candidateTask.validate();
const updatedTask = updateTask(id, req.body);
return res.json({ task: updatedTask });
} catch (error) {
console.error('Failed to read tasks data:', error);
return res
.status(400)
.json({ error: error.message || 'Failed to update task' });
}
});
app.delete('/tasks/:id', (req, res) => {
try {
const id = Number.parseInt(req.params.id, 10);
if (Number.isNaN(id)) {
return res.status(400).json({ error: 'Invalid task id' });
}
const deletedTask = deleteTask(id);
if (!deletedTask) {
return res.status(404).json({ error: 'Task not found' });
}
return res.json({ message: 'Task deleted', task: deletedTask });
} catch {
return res.status(500).json({ error: 'Failed to delete task' });
}
});
return app;
}