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.
@vitaly-t pg-promise rely on a library for promises. Native promises do not have the "finally" block. So if you use native Promises, you must always have a catch & a then block to be sure to close the connection. With this code, you can wrap all your query in a function, and the database connection will be closed automatically. That's what I was looking for when I wrote this: autoclose the connection.