I am trying to write a REST API which based on the request payload picks a database and performs certain actions.
As per the documentation, I am releasing the shared connection object at the end of the operation and the follows it through by ending the pgp application.
var pgp = require('pg-promise')();
var connection = {
user: 'generaluser', //env var: PGUSER
database: 'seeddb', //env var: PGDATABASE
password: '$$$$$$$', //env var: PGPASSWORD
host: 'localhost', // Server hosting the postgres database
port: 5432 //env var: PGPORT
};
var sco;
module.exports = {
getuser: function(req, res)
{
Account.findOne({ select: [ 'database' ], where: { appid: req.body.appid } })
.then(function (result)
{
connection.database = result.database;
var db = pgp(connection);
return db.connect();
})
.then(function (obj)
{
sco = obj;
return sco.any("select * from users");
})
.then(function (result)
{
console.log(result);
return sco.done();
})
.done(function ()
{
pgp.end();
return res.ok("Done");
});
}
};
Despite of this, I keep getting the below error from the second API call(to the same database) onwards:
WARNING: Creating a duplicate database object for the same connection.
Can someone help me with either of the following
Thanks
Terminate the application properly at the end of each call
You should absolutely NOT do it, shutting down the whole connection pool after each query is a terrible idea.
Reuse the pgp connection object on subsequent calls
What's the complication? Are you askign how to reuse objects in Node.js?
See also: Where should I initialize pg-promise.
And you should stay away from using method db.connect
like that, it is not a good way to use the framework. You should rely on the automatic connections instead ;)