I am creating code using just the pg module, where I have a general function for executing queries. This function can create a client on the spot if it doesn't take an already existing client as an argument. Or it can use an already existing client to execute a query. So I can call this function like (pseudocode)
const {Client} = require('pg');
const clientobj = {user:...}
generalQuery(text, params, client){
if !client{client = new Client(clientobj);}
client.query(text , params)
client.end();
else
client = client
client.query(text , params)
return query results
}
call like
generalQuery(text, params, false)
or via another function that already created a client
anotherFunction(){
client = new Client(clientobj);
client.query(insert)...
do some things with the results
generalQuery(text, params, client)
do some things with the results
now client.end();
}
exports.anotherFunction= anotherFunction;
exports.generalQuery= generalQuery;
So, if I have an already created client, I dont need to create another one in generalQuery
and I disconnect the client only after the results are returned in the anotherFunction
. Plus I can call the generalQuery
"as is" anytime I want and it will handle the rest.
How does pg-promise can handle that? Except special occasions, in general, it doesnt expose a client
.
So I guess I have to refactor my code and have a general query function, that will always handle client connection and disconnection internally, and never call this function with an already existing client. Pseudocode
const pgp = require('pg-promise')();
const db = pgp(connection);
generalQuery(text, params){
db.any(text, params)//all client connection/disconnection is handled here
.then(function(data) {
// success;
})
.catch(function(error) {
// error;
});
}
call like
generalQuery(text, params)
or via another function that never has an already created client
anotherFunction(){
generalQuery(text, params)
do some things with the results
generalQuery(text, params)
do some things with the results
}
exports.anotherFunction= anotherFunction;
exports.generalQuery= generalQuery;
So, with the pg-promise, there is no need to have the logic of my first example, and only the general query function creates and handles connections. Does this mean that it also automatically handles disconnections? Please advice if I am doing anything wrong or if I am missing something important.
Thank you