Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
207 lines (178 loc) · 5.99 KB
/
Copy pathserver.js
File metadata and controls
207 lines (178 loc) · 5.99 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
'use strict';
/**
* Live API Simulation
* -------------------
* Zero-dependency Node server.
*
* GET /api -> the configured JSON (with an injected _meta block)
* GET /api/raw -> the configured JSON, exactly as entered
* GET /api/config -> current config for the control panel
* PUT /api/config -> { data, refreshIntervalSeconds } - update data / timing
* GET / -> control panel (edit data, set refresh interval)
*
* State is persisted to db.json next to this file.
*/
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = process.env.PORT || 3000;
const DB_FILE = path.join(__dirname, 'db.json');
const PANEL_FILE = path.join(__dirname, 'public', 'index.html');
const DEFAULT_STATE = {
refreshIntervalSeconds: 10,
revision: 1,
updatedAt: new Date().toISOString(),
data: {
message: 'Hello from the Live API Simulation',
serverTime: '{{timestamp}}',
revision: '{{revision}}',
randomValue: '{{random}}',
users: [
{ id: 1, name: 'Ada Lovelace', active: true },
{ id: 2, name: 'Alan Turing', active: false },
],
},
};
// --- state -----------------------------------------------------------------
let state = loadState();
function loadState() {
try {
const raw = fs.readFileSync(DB_FILE, 'utf8');
const parsed = JSON.parse(raw);
return { ...DEFAULT_STATE, ...parsed };
} catch {
return { ...DEFAULT_STATE };
}
}
function saveState() {
fs.writeFileSync(DB_FILE, JSON.stringify(state, null, 2));
}
// Background "refresh": every N seconds bump the revision + timestamp so the
// API looks like it is updating on its own, even without edits.
let refreshTimer = null;
function scheduleRefresh() {
if (refreshTimer) clearInterval(refreshTimer);
const ms = Math.max(1, Number(state.refreshIntervalSeconds) || 1) * 1000;
refreshTimer = setInterval(() => {
state.revision += 1;
state.updatedAt = new Date().toISOString();
saveState();
}, ms);
refreshTimer.unref?.();
}
scheduleRefresh();
// --- templating ----------------------------------------------------------
// Replace {{tokens}} in string values so responses can carry live data.
function render(value) {
if (typeof value === 'string') {
return value
.replace(/\{\{\s*timestamp\s*\}\}/g, new Date().toISOString())
.replace(/\{\{\s*epoch\s*\}\}/g, String(Date.now()))
.replace(/\{\{\s*revision\s*\}\}/g, String(state.revision))
.replace(/\{\{\s*random\s*\}\}/g, String(Math.floor(Math.random() * 1000)));
}
if (Array.isArray(value)) return value.map(render);
if (value && typeof value === 'object') {
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, render(v)]));
}
return value;
}
// --- helpers -----------------------------------------------------------------
function sendJson(res, status, body) {
const payload = JSON.stringify(body, null, 2);
res.writeHead(status, {
'Content-Type': 'application/json; charset=utf-8',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, PUT, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Cache-Control': 'no-store',
});
res.end(payload);
}
function readBody(req) {
return new Promise((resolve, reject) => {
let raw = '';
req.on('data', (chunk) => {
raw += chunk;
if (raw.length > 5_000_000) reject(new Error('Body too large'));
});
req.on('end', () => resolve(raw));
req.on('error', reject);
});
}
// --- routing ---------------------------------------------------------------
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
const route = `${req.method} ${url.pathname}`;
if (req.method === 'OPTIONS') return sendJson(res, 204, {});
// The API
if (route === 'GET /api') {
return sendJson(res, 200, {
...render(state.data),
_meta: {
revision: state.revision,
updatedAt: state.updatedAt,
generatedAt: new Date().toISOString(),
refreshIntervalSeconds: state.refreshIntervalSeconds,
},
});
}
if (route === 'GET /api/raw') {
return sendJson(res, 200, state.data);
}
// Config for the control panel
if (route === 'GET /api/config') {
return sendJson(res, 200, {
data: state.data,
refreshIntervalSeconds: state.refreshIntervalSeconds,
revision: state.revision,
updatedAt: state.updatedAt,
});
}
if (route === 'PUT /api/config') {
try {
const body = JSON.parse((await readBody(req)) || '{}');
if (body.data !== undefined) {
state.data = body.data;
}
if (body.refreshIntervalSeconds !== undefined) {
const n = Number(body.refreshIntervalSeconds);
if (!Number.isFinite(n) || n < 1) {
return sendJson(res, 400, { error: 'refreshIntervalSeconds must be a number >= 1' });
}
state.refreshIntervalSeconds = n;
}
state.revision += 1;
state.updatedAt = new Date().toISOString();
saveState();
scheduleRefresh();
return sendJson(res, 200, {
ok: true,
data: state.data,
refreshIntervalSeconds: state.refreshIntervalSeconds,
revision: state.revision,
updatedAt: state.updatedAt,
});
} catch (err) {
return sendJson(res, 400, { error: `Invalid JSON: ${err.message}` });
}
}
// Control panel
if (route === 'GET /' || route === 'GET/index.html') {
fs.readFile(PANEL_FILE, (err, buf) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
return res.end('Control panel not found');
}
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(buf);
});
return;
}
sendJson(res, 404, { error: 'Not found', route });
});
server.listen(PORT, () => {
console.log(`Live API Simulation running`);
console.log(` Control panel : http://localhost:${PORT}/`);
console.log(` API : http://localhost:${PORT}/api`);
});