How to convert a Heroku Postgres Client to a Pool?

Viewed 82

So I am currently using the following:

const { Client } = require('pg');
const db = new Client({
  connectionString: process.env.DATABASE_URL,
  ssl: {
    rejectUnauthorized: false
  }
});

I'd like to start using pools because it seems to handle multiple users accessing the database much more efficiently...how can I convert the above into a pool? I tried just changing the word 'Client' to 'Pool,' but based on the docs it seems like pools are initialized differently. Here (https://node-postgres.com/api/pool) it shows a config object is made, and I assume I have to make one of those but I'm not exactly sure what to put inside it as I'm deploying to Heroku....any help much appreciated!

1 Answers

In theory, you should just be able to replace Client with Pool. The various other options are mainly just for configuring the size of the pool & timeouts. You shouldn't need to mess with these until you scale up your app significantly.

You will need to do extra work if you are using transactions as you would need to explicitly connect and release a client within the pool to ensure all your statements within the transaction were executed on the same connection.

Having said that, you may be better off with a higher level client such as https://www.atdatabases.org (Disclamer: I am the author of @databases). This has more complete documentation and should be easier to get started with. @databases always uses connection pools:

Related