All files / src/connection after-connect-hook.ts

100% Statements 19/19
66.66% Branches 4/6
90% Functions 9/10
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68            131x   131x       795x 795x   4x 4x   4x 4x       131x 826x 791x 35x                                 797x                 816x         826x   795x 791x 826x     816x      
import { Client as PgClient, type PoolConfig } from 'pg';
 
type PoolClientClass = NonNullable<PoolConfig['Client']>;
type ConnectCallback = (error: Error) => void;
 
/** Errors thrown by an `afterConnect` hook; v6 surfaces them unchanged, so they skip connection error mapping. */
export const hookFailures = new WeakSet<object>();
 
const runAfterConnect = async (
  client: PgClient,
  run: (client: PgClient) => Promise<void>,
): Promise<void> => {
  try {
    await run(client);
  } catch (error) {
    Eif (typeof error === 'object' && error !== null) {
      hookFailures.add(error);
    }
    client.end().catch(() => {});
    throw error;
  }
};
 
const settle = (connected: Promise<unknown>, callback: ConnectCallback): void => {
  connected.then(
    () => (callback as unknown as (error: null) => void)(null),
    (error: unknown) => callback(error as Error),
  );
};
 
/**
 * Runs the `afterConnect` hook on every new pooled connection, before the pool hands it out.
 * `pg` has no portable async connect hook (`onConnect` needs a recent `pg-pool`), so the pool
 * is given a `pg.Client` subclass whose `connect()` runs the hook once the client is connected;
 * when the hook throws the client is closed and the error reaches the caller of the query.
 */
export class AfterConnectHook {
  readonly #run: (client: PgClient) => Promise<void>;
 
  /**
   * @param run - Hook runner; receives the connected client.
   */
  constructor(run: (client: PgClient) => Promise<void>) {
    this.#run = run;
  }
 
  /**
   * Client class for the `Client` pool option.
   *
   * @returns `pg.Client` subclass that runs the hook after connecting.
   */
  clientClass(): PoolClientClass {
    const run = this.#run;
    class HookedClient extends PgClient {
      override connect(): Promise<this>;
      override connect(callback: ConnectCallback): void;
      override connect(callback?: ConnectCallback): Promise<this> | void {
        const connected = super
          .connect()
          .then(() => runAfterConnect(this, run))
          .then(() => this);
        return callback === undefined ? connected : settle(connected, callback);
      }
    }
    return HookedClient as unknown as PoolClientClass;
  }
}