I have a server which I've written using Express and node-postgres (pg). It creates its own DB pool:
const dbPool = new pg.Pool(dbConfig);
and runs SQL queries directly using this connection.
Now I'm adding a new table and corresponding REST API. I'd like to use sequelize and epilogue to reduce the boilerplate. Unfortunately, sequelize wants to create its own database connection pool:
const sequelize = new Sequelize(database, user, password, config);
Is it possible to re-use the existing connection pool or otherwise share it between my existing pg
code and my new sequelize
code?
The pool is the collection of these saved, reusable connections that, in your case, Sequelize pulls from. Your configuration of pool: { max: 5, min: 0, idle: 10000 } reflects that your pool should: Never have more than five open connections ( max: 5 )
For this application, we'll use Sequelize as ORM, as it supports multiple dialects, one of which is PostgreSQL. Sequelize provides a comfortable API to work with PostgreSQL databases from setup to execution, but there are many ORMs (e.g. TypeORM, Objection. js) to choose from for a Node.
Sequelize does not offer the option to pass a custom pool, but you can pass options that will get used to create the sequelize pool, such as min and max connections.
What I would do in your case is to check your total DB connection count, and make a repartition based on the expected usage of your two pools.
For example if you have 20 connections max on your database:
const dbPool = new pg.Pool({
max: 10
});
const sequelize = new Sequelize(/* ... */, {
// ...
pool: {
max: 10,
min: 0,
acquire: 30000,
idle: 10000
}
});
I would also suggest using environment variables to set the max connection on your sequelize pool and nod-pg pool, so that you could adapt easily your repartition if needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With