Files
stocca-tre/server/database.ts
2022-07-08 09:31:34 +02:00

43 lines
1.3 KiB
TypeScript

import { Client } from "postgres";
import config from "./config.ts";
import {Maybe} from "./Maybe.ts";
import {JSONObject} from "./JSON.ts";
export type WithoutId<T> = Omit<T, "id">;
export interface StoccaTreDbConn {
query<T extends JSONObject | JSONObject[]>(query: string): Promise<Maybe<T>>,
}
export default function createNewDbConnection(): StoccaTreDbConn {
const postgresClient = new Client({
hostname: config.hostname,
password: config.password,
user: config.username,
database: "stocca_tre",
port: config.port,
});
await postgresClient.connect();
return {
async queryMany<T extends JSONObject[]>(query: string): Promise<Maybe<{ rows: T, count: number }>> {
try {
const result = await postgresClient.queryArray<T>(query);
return {
just: {
rows: result.rows,
count: result.rowCount ?? NaN,
},
};
} catch (e: unknown) {
}
},
queryOne<T extends JSONObject>(query: string): Promise<Maybe<T>> {
try {
const result = await postgresClient.queryObject<T>(query);
return { just: result };
}
}
}
}