I am the author of pg-promise , which simplifies the use of node-postgres through promises.
It addresses the problems of properly connecting and disconnecting from the database using the connection pool implemented by node-postgres , among other things, as automated transactions.
An individual pg-promise request comes down to what is relevant to your business logic:
db.any('SELECT * FROM users WHERE status = $1', ['active']) .then(data => { console.log('DATA:', data); }) .catch(error => { console.log('ERROR:', error); });
i.e. you do not need to deal with the connection logic when executing queries, because you only establish a connection once, globally, for example:
const pgp = require('pg-promise')(/*options*/); const cn = { host: 'localhost', // server name or IP address; port: 5432, database: 'myDatabase', user: 'myUser', password: 'myPassword' }; // alternative: // const cn = 'postgres://username:password@host:port/database'; const db = pgp(cn); // database instance;
You can find many more examples in Learn by Example or on the main page of the project .
vitaly-t May 16 '15 at 18:36 2015-05-16 18:36
source share