// lib/db.js: each user's notes 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. The platform applies the // files under migrations/ before a version serves, so the table stands when a // function first reads it. let pool; async function query(text, values) { 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 }).on('error', (error) => console.error(error.message)); return pool.query(text, values); } // The data layer over any query function with pg's shape: the live one, or a // test double's. Each row belongs to the signed-in user who added it, its // owner, and is listed to that user alone, newest first; only its owner can // delete it. export function createDataLayer(run) { return { async addNote(owner, body) { const { rows } = await run('INSERT INTO "notes" (owner, body) VALUES ($1, $2) RETURNING id, body, created_at', [owner, body]); return rows[0]; }, async listNotes(owner) { const { rows } = await run('SELECT id, body, created_at FROM "notes" WHERE owner = $1 ORDER BY created_at DESC, id DESC', [owner]); return rows; }, // True where the row was the owner's and is gone; false where no row of the owner's has the id. async deleteNote(owner, id) { const { rowCount } = await run('DELETE FROM "notes" WHERE owner = $1 AND id = $2', [owner, id]); return rowCount === 1; }, }; } export const notesStore = createDataLayer(query);