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.
pg-promise uses the connection pool implemented by node-postgres, which in turn redirects it into generic-pool. with pg-promise you do need to worry about keeping the connection at all.
P.S. It is awkward writing here, because posts here do not provide any notification, no way of knowing when somebody has replied.