How to make multiple db connections with pg for multi tenancy?

26 Views Asked by At

I developing a multi tenancy SaaS. I use subdomains for my clients and I know how I extract the subdomain and make a query etc. But I dont know what is the best way to make multiple db connections because I use for every client a new db with different schema (some schema maybe same).

So should I hard code the connections like const db1 = .., const db2 = ...

or is there a better way to do this ?

right now I do this:

const { Pool } = require('pg')
 
function construct_pool(db_name) {

  const pool = new Pool({
    host: 'dxxx',
    user: 'postgrxxxes',
    database: db_name ?? 'postgres',
    password: 'xxx',
    ssl: { rejectUnauthorized: false },
    port: 5432,
    max: 20,
    idleTimeoutMillis: 30000,
    connectionTimeoutMillis: 10000,
  });

  return pool;
}

export var connectors = {
  'db1': construct_pool('db1'),
  'db2': construct_pool('db2'),
  'db3': construct_pool('db3')
}

but is this not bad because everytime I make a new connection ? how you would do this ?

0

There are 0 best solutions below