18 Companion server.js (10/13)
const NO_GAMES = { rows: [{ title: 'No games on the server', sub: `Put .z5/.z8 files into ${GAMES_DIR}`, id: 'none' }] };
// ------------------------------------------------------------------ http
function send(res, status, body, type = 'application/json; charset=utf-8') {
const data = typeof body === 'string' ? body : JSON.stringify(body);
res.writeHead(status, { 'Content-Type': type, 'Cache-Control': 'no-store', 'Content-Length': Buffer.byteLength(data) });
res.end(data);
}
async function handle(req, res) {
const url = new URL(req.url, 'http://x');
const q = (k) => url.searchParams.get(k) || '';
const parts = url.pathname.split('/').filter(Boolean);
console.log(new Date().toISOString(), req.method, url.pathname + url.search);
if (url.pathname === '/' || url.pathname === '/health') {
const list = [...games().values()].map((g) => ` ${g.id} (${g.title}, v${g.story[0]})`).join('\n');
return send(res, 200, `Text adventure server: ${games().size} game(s)\n${list}\n`, 'text/plain; charset=utf-8');
}
if (url.pathname === '/games') {
const lists = [...games().values()].slice(0, 64).map((g) => ({ title: g.title, id: g.id }));
return send(res, 200, { lists });
}
if (parts[0] !== 's' || parts.length !== 3) return send(res, 404, { error: 'not found' });