// 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; }; export function createAppServer(db) { return createServer(async (request, response) => { // The deployed runtime's abort signal: end the response when it fires. request.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' }); } }); }