This pattern is a pattern I use for all my Node projects that need PostgreSQL. I work a lot with Promises, and ended-up designing this db.js
file.
Put this file wherever you want in your app directory. Edit the connectionInfo
string and voilà!
Call the execute
method passing a callback function. Your callback function will be called with a function as first parameter which will allow you to execute SQL queries retourning Promises. Execute as much queries as you want, but don't forget to return a Promise that must be resolved once all your queries are done. After that, the database connection will be properly closed automatically.
That is incorrect. Closing the connection is optional, and done only once, in the end of the application, requests do not have to deal with connections at all. See the examples: Learn by Example
And ES6 Promise is the default library used by pg-promise.