ls-deno/db/mod.ts
2022-10-07 23:22:35 -05:00

87 lines
2.1 KiB
TypeScript

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<T>(
sql: string,
...args: QueryArguments[]
): Promise<QueryObjectResult<T> | null> {
let result = null;
try {
const connection = await pool.connect();
try {
result = await connection.queryObject<T>({
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<T extends unknown>(
sql: string,
...args: QueryArguments[]
): Promise<QueryArrayResult<T[]> | null> {
let result = null;
try {
const connection = await pool.connect();
try {
result = await connection.queryArray<T[]>({
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<Note>(
"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 =", idVal);
return await queryObject<Note>(
"select * from note where id = $1",
[idVal],
);
}
export async function createNote({ content }: Omit<Note, "id" | "createdAt">) {
return await queryObject<Note>(
"insert into note (content) values ($1) returning *",
[content],
);
}