ls-deno/db/mod.ts

128 lines
3.2 KiB
TypeScript
Raw Normal View History

2022-09-30 15:14:57 -05:00
import {
Pool,
2022-10-08 00:00:45 -05:00
PoolClient,
2022-09-30 15:14:57 -05:00
PostgresError,
} from "https://deno.land/x/postgres@v0.16.1/mod.ts";
import {
type QueryArguments,
2022-10-07 23:22:35 -05:00
type QueryArrayResult,
2022-09-30 15:14:57 -05:00
type QueryObjectResult,
} from "https://deno.land/x/postgres@v0.16.1/query/query.ts?s=QueryArguments";
2022-10-07 23:22:35 -05:00
import { config } from "@/config.ts";
2022-10-08 00:00:45 -05:00
import {
type Identifiable,
type Note,
type Timestamped,
type User,
} from "@/types.ts";
2022-09-27 15:49:41 -05:00
2022-09-30 15:14:57 -05:00
export { PostgresError };
export { type QueryObjectResult };
2022-09-27 15:49:41 -05:00
2022-10-07 23:22:35 -05:00
const pool = new Pool(config.postgres.url, 3, true);
2022-09-27 15:49:41 -05:00
2022-10-08 00:00:45 -05:00
async function dbOp<T>(op: (connection: PoolClient) => Promise<T>) {
2022-09-27 15:49:41 -05:00
let result = null;
2022-10-08 00:00:45 -05:00
let exception = null;
2022-09-27 15:49:41 -05:00
try {
const connection = await pool.connect();
try {
2022-10-08 00:00:45 -05:00
result = await op(connection);
2022-09-27 15:49:41 -05:00
} catch (err) {
2022-10-07 23:22:35 -05:00
console.error("Error querying database:", { ...err });
2022-10-08 00:00:45 -05:00
exception = err;
2022-09-27 15:49:41 -05:00
} finally {
connection.release();
}
} catch (err) {
2022-10-08 00:00:45 -05:00
exception = err;
2022-09-27 15:49:41 -05:00
console.error("Error connecting to database:", err);
}
2022-10-08 00:00:45 -05:00
if (exception != null) throw exception;
2022-09-27 15:49:41 -05:00
return result;
}
2022-10-07 23:22:35 -05:00
2022-10-08 00:00:45 -05:00
export async function queryObject<T>(
2022-10-07 23:22:35 -05:00
sql: string,
2022-10-08 00:00:45 -05:00
args?: QueryArguments,
): Promise<QueryObjectResult<T> | null> {
return await dbOp(async (connection) =>
await connection.queryObject<T>({
camelcase: true,
text: sql.trim(),
args,
})
);
}
export async function queryArray<T extends []>(
sql: string,
args?: QueryArguments,
): Promise<QueryArrayResult<T> | null> {
return await dbOp(async (connection) =>
await connection.queryArray<T>({
text: sql.trim(),
args,
})
);
2022-10-07 23:22:35 -05:00
}
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;
2022-10-07 23:29:34 -05:00
console.debug("getNote id =", JSON.stringify(idVal));
2022-10-07 23:22:35 -05:00
return await queryObject<Note>(
"select * from note where id = $1",
[idVal],
);
}
2022-10-08 00:00:45 -05:00
type Ungenerated<T> = Omit<T, keyof Identifiable | keyof Timestamped>;
export async function createNote({ content }: Ungenerated<Note>) {
2022-10-07 23:22:35 -05:00
return await queryObject<Note>(
"insert into note (content) values ($1) returning *",
[content],
);
}
2022-10-08 00:00:45 -05:00
export async function createUser(
{ username, passwordDigest }: Ungenerated<User>,
) {
return await queryObject<{ user_id: string }>(
`
with new_user as (
insert into "user" (username, password_digest, status)
values ($username, $passwordDigest, 'unverified')
returning id as user_id
), new_team as (
insert into "team" (display_name)
values ($teamName)
returning id as team_id
)
insert into "team_user" (user_id, team_id, status)
values (
(select user_id from new_user),
(select team_id from new_team),
'owner'
) returning user_id
`,
{ username, passwordDigest, teamName: `${username}'s First Team` },
);
}
export async function getUser({ id, username }: Partial<User>) {
if (!id && !username) throw "getUser called without id or username";
const column = id ? "id" : "username";
return await queryObject<User>(
`select * from "user" where "${column}" = $1`,
[id || username],
);
}