// src/server.mjs import { createServer } from 'node:http'; const readBody = async (request) => { // One decoder for the whole body: a character whose bytes arrive in two chunks is read whole. request.setEncoding('utf8'); let text = ''; for await (const chunk of request) text += chunk; return text; }; // A request's abort signal. The deployed runtime attaches its own signal to each // request, and it aborts at the request's window. A local run has none of its own, // and Node's request.signal can abort at a normal request end on some Node 24 // releases, so a local run's signal aborts when the response closes unfinished. function abortSignalOf(request, response) { const own = Object.hasOwn(request, 'signal') ? request.signal : undefined; if (own) return own; const controller = new AbortController(); response.once('close', () => { if (!response.writableFinished) controller.abort(); }); return controller.signal; } export function createAppServer(db) { return createServer(async (request, response) => { // End the response when the request is aborted (abortSignalOf, above). const signal = abortSignalOf(request, response); signal.addEventListener('abort', () => response.destroy(), { once: true }); const send = (status, body) => { if (response.destroyed) return; response.writeHead(status, { 'content-type': 'application/json' }); response.end(JSON.stringify(body)); }; try { // A target that does not parse as a URL names no route, so it is answered 404 below. let pathname = null; try { pathname = new URL(request.url, 'http://localhost').pathname; } catch {} if (request.method === 'GET' && pathname === '/health') { return (await db.reachable()) ? send(200, { ok: true }) : send(503, { ok: false }); } if (request.method === 'GET' && pathname === '/notes') return send(200, await db.listNotes()); if (request.method === 'POST' && pathname === '/notes') { const posted = JSON.parse(await readBody(request)); return send(201, await db.addNote(String(posted?.title ?? ''))); } send(404, { error: 'not_found' }); } catch (error) { const refused = error instanceof SyntaxError ? 'invalid_json' : error?.code === '23514' ? 'invalid_note' : null; if (refused === null) console.error(error); send(refused === null ? 500 : 400, { error: refused ?? 'internal' }); } }); }