I have a background process in NodeJS that connects to PSQL. And the background process is quite busy in I/O.
I'm using pg-pool submodule to maintain connection pool. I need to know the best way of implementing pooling globally, in that way pg connections won't get leaked in the applications.
Global module to be included in every file.
// psql.js
const pg = require('pg')
const {
parse,
} = require('pg-connection-string')
const pgCred = "postgres://db-user:password@localhost:5432/db-name"
class PsqlConnector{
constructor () {
this.db = undefined
this.connect = this.connect.bind(this)
this.get = this.get.bind(this)
}
/**
* estalibshes db connection
*/
async connect (url) {
if (this.db) {
console.log('psql db connection already exist')
return this.db
} else if (pgCred) { // Will come from env variable.
const config = parse(pgCred)
const pgPool = new pg.Pool(config)
return pgPool.connect()
.then((conn) => {
console.log('psql db connection established')
this.db = conn
return this.db
}).catch((e) => {
console.log(e.toString())
throw e
})
}
}
async get (query) {
return this.connect()
.then((db) => {
return db.query(query)
})
}
}
module.exports = new PsqlConnector()
Example code to connect to PSQL
// users.js
const psql = require('psql')
psql.get('select * from users limit 1')
.then(result => result.rows)
Is the above strategy violates any node-postgres rules?
And will the above code prevent the application from leaking connections?
Note:
In the below code, I tried to release the client after each query executed. But db.release() returns an error stating that Release called on client which has already been released to the pool. (This happens when the second query is getting executed through the client. The first query is not throwing any error.)
So I figured that the client is already released. Refer to the below code.
// psql.js
async get (query) {
return this.connect()
.then((db) => {
const result = db.query(query)
db.release() // Throws error.
return result
})
}
I have a background process in NodeJS that connects to PSQL. And the background process is quite busy in I/O.
I'm using pg-pool submodule to maintain connection pool. I need to know the best way of implementing pooling globally, in that way pg connections won't get leaked in the applications.
Global module to be included in every file.
Example code to connect to PSQL
Is the above strategy violates any node-postgres rules?
And will the above code prevent the application from leaking connections?
Note:
In the below code, I tried to release the client after each query executed. But
db.release()returns an error stating thatRelease called on client which has already been released to the pool.(This happens when the second query is getting executed through the client. The first query is not throwing any error.)So I figured that the client is already released. Refer to the below code.