diff --git a/README.md b/README.md index 2137d9c..ba91c1e 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,7 @@ export const {db, CoreBaseModel, helpers} = initDB({ - `beforeTerminate`: Function called before terminating a connection, must return a Promise - `topologyMode`: Connection topology, either `primary-replica` (the default) or `proxy` - `knexOptions`: Non-required additional options that will be passed to Knex before initialization +- `onKnexCreated`: Optional callback called synchronously for each Knex instance created by the dispatcher, before database health checks start. Use it to attach instrumentation, event listeners, or plugins that do not require an active database connection. If it throws, initialization fails. The callback receives the Knex instance and returns nothing. When all connection strings point to equivalent proxy or router instances, such as SPQR routers, use `proxy` mode. Healthy endpoints are then eligible for both primary and replica queries, and the endpoint with the lowest latest health-check latency is selected: diff --git a/lib/dispatcher.ts b/lib/dispatcher.ts index 34851e0..38cf1ab 100644 --- a/lib/dispatcher.ts +++ b/lib/dispatcher.ts @@ -24,6 +24,8 @@ export interface PDConstructorArgs { options: PDOptions; knexOptions?: Knex.Config; logger: ExLogger; + + onKnexCreated?: (knex: Knex) => void; } interface PDConnection { @@ -52,20 +54,28 @@ export class PGDispatcher { private hcTimer?: Timeout | null; private isInit = false; - constructor({connections = [], options, knexOptions = {}, logger}: PDConstructorArgs) { + constructor({ + connections = [], + options, + knexOptions = {}, + logger, + onKnexCreated, + }: PDConstructorArgs) { if (!connections.length) { throw new Error('Empty connections list is not allowed'); } this.connections = connections.map((connectionString) => { const url = new URL(connectionString); + const knex = knexBuilder({ + ...knexOptions, + client: 'pg', + connection: connectionString, + }); + onKnexCreated?.(knex); return { host: url.hostname, - knex: knexBuilder({ - ...knexOptions, - client: 'pg', - connection: connectionString, - }), + knex, primary: false, healthy: false, latency: Infinity,