// lib/db.js: the notes' store in the application's database. import pg from 'pg'; // One connection for this worker, opened at its first query and kept while // the worker lives. The platform supplies APP_DATABASE_URL, and the turnzero // command's provision writes it for a local run. let pool; function database() { const url = process.env.APP_DATABASE_URL; if (!url) throw new Error('APP_DATABASE_URL is not set'); pool ??= new pg.Pool({ connectionString: url, max: 1, connectionTimeoutMillis: 5000 }); return pool; } // The platform applies the files under migrations/ before a version serves, // so the table stands when a function first reads it. export const notesStore = { async addNote(title) { const { rows } = await database().query('INSERT INTO "notes" (title) VALUES ($1) RETURNING id, title', [title]); return rows[0]; }, async listNotes() { const { rows } = await database().query('SELECT id, title FROM "notes" ORDER BY id'); return rows; }, };