import { Pool, PostgresError, } from "https://deno.land/x/postgres@v0.16.1/mod.ts"; import { type QueryArguments, type QueryArrayResult, type QueryObjectResult, } from "https://deno.land/x/postgres@v0.16.1/query/query.ts?s=QueryArguments"; import { config } from "@/config.ts"; import { type Note } from "@/types.ts"; export { PostgresError }; export { type QueryObjectResult }; const pool = new Pool(config.postgres.url, 3, true); export async function queryObject( sql: string, args: QueryArguments[], ): Promise | null> { let result = null; try { const connection = await pool.connect(); try { result = await connection.queryObject({ camelcase: true, text: sql, args, }); } catch (err) { console.error("Error querying database:", { ...err }); } finally { connection.release(); } } catch (err) { console.error("Error connecting to database:", err); } return result; } export async function queryArray( sql: string, args: QueryArguments[], ): Promise | null> { let result = null; try { const connection = await pool.connect(); try { result = await connection.queryArray({ text: sql, args, }); } catch (err) { console.error("Error querying database:", { ...err }); } finally { connection.release(); } } catch (err) { console.error("Error connecting to database:", err); } return result; } export async function listNotes() { return await queryObject( "select * from note order by created_at desc", ); } export async function getNote(id: string | { id: string }) { const idVal = typeof id == "object" ? id.id : id; console.debug("getNote id =", JSON.stringify(idVal)); return await queryObject( "select * from note where id = $1", [idVal], ); } export async function createNote({ content }: Omit) { return await queryObject( "insert into note (content) values ($1) returning *", [content], ); }