0.1.2Updated 2 months 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 {
  private constructor() {}

  private static pool: Pool
  private static client: PoolClient

  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)
}