Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
22 changes: 16 additions & 6 deletions lib/dispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ export interface PDConstructorArgs {
options: PDOptions;
knexOptions?: Knex.Config;
logger: ExLogger;

onKnexCreated?: (knex: Knex) => void;
}

interface PDConnection {
Expand Down Expand Up @@ -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,
Expand Down
Loading