@refpool/knex
v0.1.0
Published
Multi-tenant Knex instance pooling built on @refpool/core's reference-counted, bounded LRU pool.
Maintainers
Readme
@refpool/knex
Multi-tenant Knex instance pooling built on @refpool/core's
reference-counted, bounded LRU pool.
A pool of Knex instances keyed by tenant — bounded at max, shared between
concurrent requests for the same tenant, with idle instances .destroy()ed
automatically.
Install
npm install @refpool/knex knexknex (^3.0.0) is a required peer dependency — this package statically
imports it, so you must install knex alongside @refpool/knex.
Usage
import { createKnexPool, withResource } from '@refpool/knex';
const pool = createKnexPool({
max: 20,
idleTtlMs: 60_000,
config: (tenantId) => ({
client: 'pg',
connection: `postgres://localhost:5432/tenant_${tenantId}`,
pool: { min: 0, max: 5 }, // inner Knex pool, per tenant
}),
});
pool.start();
const users = await withResource(pool, tenantId, (db) => db('users').select('*'));
await pool.stop(); // on shutdown: destroys every live Knex instanceThe factory builds a Knex instance from config(key); dispose calls
.destroy() on eviction/drain. All other PoolOptions
pass through.
API
createKnexPool(options)→RefCountedLruPool<Knex>—optionsisPoolOptionsminusfactory/dispose, plusconfig: (key) => Knex.Config | Promise<Knex.Config>.withResource(pool, key, fn)— acquirekey, runfn(knex), release infinally.
License
MIT © Atul Singh
