// lib/notes.js: the notes API over any store. Code under lib/ is shared by the // functions and answers no path. functions/api/notes.js gives this API the // database's store, and the tests give it a double. const json = (body, status = 200, headers = {}) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', ...headers } }); // The page's input has the same bound. The function checks it too, since a // request need not come from the page. const TITLE_MAX = 200; // GET lists the notes, oldest first. POST adds one from { "title": "..." }. export function createNotesApi(store) { return async function fetch(request) { if (request.method === 'GET') return json({ notes: await store.listNotes() }); if (request.method === 'POST') { let sent; try { sent = await request.json(); } catch { sent = null; } const title = typeof sent?.title === 'string' ? sent.title.trim() : ''; if (title === '' || title.length > TITLE_MAX) return json({ error: 'invalid_request', detail: `Send a JSON object with a title of 1 to ${TITLE_MAX} characters.` }, 400); const note = await store.addNote(title); // A function's console lines reach the application's logs. console.log(`note ${note.id} added`); return json(note, 201); } return json({ error: 'method_not_allowed', detail: 'This path takes GET and POST.' }, 405, { allow: 'GET, POST' }); }; }