-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
144 lines (125 loc) · 4.38 KB
/
server.js
File metadata and controls
144 lines (125 loc) · 4.38 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
const http = require('http');
const fs = require('fs');
const path = require('path');
const host = process.env.HOST || '0.0.0.0';
const port = Number(process.env.PORT || 3000);
const publicDir = path.join(__dirname, 'public');
const dataFile = path.join(__dirname, 'data', 'todos.json');
fs.mkdirSync(path.dirname(dataFile), { recursive: true });
if (!fs.existsSync(dataFile)) {
fs.writeFileSync(dataFile, '[]\n', 'utf8');
}
function sendJson(res, status, payload) {
res.writeHead(status, {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store'
});
res.end(JSON.stringify(payload));
}
function readTodos() {
try {
return JSON.parse(fs.readFileSync(dataFile, 'utf8'));
} catch {
return [];
}
}
function writeTodos(todos) {
fs.writeFileSync(dataFile, JSON.stringify(todos, null, 2) + '\n', 'utf8');
}
function parseBody(req) {
return new Promise((resolve, reject) => {
let body = '';
req.on('data', chunk => {
body += chunk;
if (body.length > 1_000_000) {
reject(new Error('Body too large'));
req.destroy();
}
});
req.on('end', () => {
if (!body) return resolve({});
try {
resolve(JSON.parse(body));
} catch {
reject(new Error('Invalid JSON body'));
}
});
req.on('error', reject);
});
}
function serveStatic(res, filePath, contentType) {
try {
const content = fs.readFileSync(filePath);
res.writeHead(200, { 'Content-Type': contentType + '; charset=utf-8' });
res.end(content);
} catch {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Not found');
}
}
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host || `${host}:${port}`}`);
if (req.method === 'GET' && (url.pathname === '/health' || url.pathname === '/api/health')) {
return sendJson(res, 200, { ok: true, service: 'todo-prototype', port, host });
}
if (req.method === 'GET' && url.pathname === '/api/todos') {
return sendJson(res, 200, { todos: readTodos() });
}
if (req.method === 'POST' && url.pathname === '/api/todos') {
try {
const body = await parseBody(req);
const text = String(body.text || '').trim();
if (!text) return sendJson(res, 400, { error: 'Todo text is required' });
const todos = readTodos();
const todo = {
id: Date.now().toString(36),
text,
completed: false,
createdAt: new Date().toISOString()
};
todos.unshift(todo);
writeTodos(todos);
return sendJson(res, 201, { todo, todos });
} catch (error) {
return sendJson(res, 400, { error: error.message });
}
}
if (req.method === 'PATCH' && url.pathname.startsWith('/api/todos/')) {
try {
const id = url.pathname.split('/').pop();
const body = await parseBody(req);
const todos = readTodos();
const index = todos.findIndex(todo => todo.id === id);
if (index === -1) return sendJson(res, 404, { error: 'Todo not found' });
todos[index] = { ...todos[index], completed: Boolean(body.completed) };
writeTodos(todos);
return sendJson(res, 200, { todo: todos[index], todos });
} catch (error) {
return sendJson(res, 400, { error: error.message });
}
}
if (req.method === 'DELETE' && url.pathname.startsWith('/api/todos/')) {
const id = url.pathname.split('/').pop();
const todos = readTodos();
const nextTodos = todos.filter(todo => todo.id !== id);
if (nextTodos.length === todos.length) {
return sendJson(res, 404, { error: 'Todo not found' });
}
writeTodos(nextTodos);
return sendJson(res, 200, { deleted: id, todos: nextTodos });
}
if (req.method === 'GET' && (url.pathname === '/' || url.pathname === '/index.html')) {
return serveStatic(res, path.join(publicDir, 'index.html'), 'text/html');
}
if (req.method === 'GET' && url.pathname === '/styles.css') {
return serveStatic(res, path.join(publicDir, 'styles.css'), 'text/css');
}
if (req.method === 'GET' && url.pathname === '/app.js') {
return serveStatic(res, path.join(publicDir, 'app.js'), 'application/javascript');
}
res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ error: 'Not found' }));
});
server.listen(port, host, () => {
console.log(`TODO prototype listening on http://${host}:${port}`);
});