0.1.5•Updated 12 days ago
import { Pool } from 'jsr:@db/postgres';
import type { ClientOptions, PoolClient, QueryObjectResult } from 'jsr:@db/postgres';
import Environment from "../modules/environment.ts";
const { options, POOL_COUNT, AUTO_CONNECT } = Environment;
export class Postgres {
pool?: Pool
client?: PoolClient
constructor(readonly options: ClientOptions) {
}
async Setup() {
if(this.pool) {
await this.pool.end();
}
this.pool = new Pool(this.options, POOL_COUNT, true);
this.client = await this.pool.connect();
return this;
}
async query<T = unknown>(clause: string, args?: unknown[]): Promise<QueryObjectResult<T> | { rows: [], rowCount: 0 }> {
try {
return await this.client!.queryObject<T>(clause, args);
// deno-lint-ignore no-explicit-any
} catch (e: any) {
console.error(clause, args);
console.warn(e.message);
console.warn(e.stack);
return { rows: [], rowCount: 0 };
}
}
private static pool: Pool
private static client: PoolClient
static get IsConfigured() {
return this.client?.connected;
}
static readonly Config = Object.freeze(options)
static async query<T = unknown>(clause: string, args?: unknown[]): Promise<QueryObjectResult<T> | { rows: [], rowCount: 0 }> {
try {
return await this.client.queryObject<T>(clause, args);
// deno-lint-ignore no-explicit-any
} catch (e: any) {
console.error(clause, args);
console.warn(e.message);
console.warn(e.stack);
return { rows: [], rowCount: 0 };
}
}
static async Setup(options_override?: ClientOptions) {
if(this.pool) {
await this.pool.end();
}
this.pool = new Pool(options_override || this.Config, POOL_COUNT, true);
this.client = await this.pool.connect();
}
}
if(AUTO_CONNECT) {
await Postgres.Setup(options)
}