Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
180 lines (155 loc) · 6.09 KB
/
Copy pathserver.js
File metadata and controls
180 lines (155 loc) · 6.09 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
const http = require('node:http');
const fs = require('node:fs/promises');
const path = require('node:path');
const crypto = require('node:crypto');
const PORT = Number(process.env.PORT) || 3000;
const ROOT = __dirname;
const STORE_PATH = path.join(ROOT, 'data', 'store.json');
const clients = new Set();
const MIME_TYPES = {
'.css': 'text/css; charset=utf-8',
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png'
};
async function readStore() {
return JSON.parse(await fs.readFile(STORE_PATH, 'utf8'));
}
async function writeStore(store) {
await fs.writeFile(STORE_PATH, `${JSON.stringify(store, null, 2)}\n`);
}
function sendJson(response, status, payload) {
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
response.end(JSON.stringify(payload));
}
function broadcast(event, payload) {
const message = `event: ${event}\ndata: ${JSON.stringify(payload)}\n\n`;
clients.forEach(client => client.write(message));
}
async function readBody(request) {
let body = '';
for await (const chunk of request) body += chunk;
if (!body) return {};
try {
return JSON.parse(body);
} catch {
return null;
}
}
function notificationFrom(tokenId, message, channel = 'browser') {
return {
id: crypto.randomUUID(),
tokenId,
channel,
message,
status: 'delivered',
createdAt: new Date().toISOString()
};
}
async function createNotification(store, tokenId, message, channel) {
const notification = notificationFrom(tokenId, message, channel);
store.notifications.unshift(notification);
store.notifications = store.notifications.slice(0, 100);
await writeStore(store);
broadcast('notification', notification);
return notification;
}
async function handleApi(request, response, pathname) {
const store = await readStore();
if (request.method === 'GET' && pathname === '/api/health') {
return sendJson(response, 200, { ok: true, service: 'DigiToken API' });
}
if (request.method === 'GET' && pathname === '/api/queue') {
return sendJson(response, 200, { tokens: store.tokens });
}
if (request.method === 'GET' && pathname === '/api/notifications') {
return sendJson(response, 200, { notifications: store.notifications });
}
if (request.method === 'GET' && pathname === '/api/events') {
response.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive'
});
response.write('retry: 5000\n\n');
clients.add(response);
request.on('close', () => clients.delete(response));
return;
}
if (request.method === 'POST' && pathname === '/api/tokens') {
const body = await readBody(request);
if (!body || !body.service) return sendJson(response, 400, { error: 'service is required' });
const prefix = body.type === 'walkin' ? 'W' : 'A';
const sequence = store.tokens.filter(token => token.id.startsWith(`${prefix}-`)).length + 1;
const token = {
id: `${prefix}-${String(sequence).padStart(3, '0')}`,
type: body.type === 'walkin' ? 'walkin' : 'online',
service: String(body.service),
status: 'waiting',
time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
};
store.tokens.push(token);
await writeStore(store);
broadcast('queue-updated', { tokens: store.tokens });
await createNotification(store, token.id, `Token ${token.id} was created and is waiting.`, body.channel);
return sendJson(response, 201, token);
}
const statusMatch = pathname.match(/^\/api\/tokens\/([^/]+)\/status$/);
if (request.method === 'PATCH' && statusMatch) {
const body = await readBody(request);
const token = store.tokens.find(item => item.id === decodeURIComponent(statusMatch[1]));
if (!token) return sendJson(response, 404, { error: 'token not found' });
if (!body || !['waiting', 'serving', 'completed', 'no-show'].includes(body.status)) {
return sendJson(response, 400, { error: 'invalid status' });
}
if (body.status === 'serving') {
store.tokens.forEach(item => {
if (item.status === 'serving') item.status = 'completed';
});
}
token.status = body.status;
await writeStore(store);
broadcast('queue-updated', { tokens: store.tokens });
const message = body.status === 'serving'
? `Your token ${token.id} is now being served.`
: `Token ${token.id} status changed to ${body.status}.`;
await createNotification(store, token.id, message, body.channel);
return sendJson(response, 200, token);
}
if (request.method === 'POST' && pathname === '/api/notifications') {
const body = await readBody(request);
if (!body || !body.message) return sendJson(response, 400, { error: 'message is required' });
const notification = await createNotification(store, body.tokenId || null, String(body.message), body.channel);
return sendJson(response, 201, notification);
}
sendJson(response, 404, { error: 'API route not found' });
}
async function serveStatic(response, pathname) {
const requestedPath = pathname === '/' ? '/index.html' : pathname;
const filePath = path.resolve(ROOT, `.${requestedPath}`);
if (!filePath.startsWith(ROOT + path.sep)) return sendJson(response, 403, { error: 'forbidden' });
try {
const content = await fs.readFile(filePath);
response.writeHead(200, { 'Content-Type': MIME_TYPES[path.extname(filePath)] || 'application/octet-stream' });
response.end(content);
} catch {
sendJson(response, 404, { error: 'file not found' });
}
}
const server = http.createServer(async (request, response) => {
const requestUrl = new URL(request.url, `http://${request.headers.host}`);
try {
if (requestUrl.pathname.startsWith('/api/')) {
await handleApi(request, response, requestUrl.pathname);
} else {
await serveStatic(response, requestUrl.pathname);
}
} catch (error) {
console.error(error);
sendJson(response, 500, { error: 'internal server error' });
}
});
server.listen(PORT, () => {
console.log(`DigiToken running at http://localhost:${PORT}`);
});