Skip to content

Instantly share code, notes, and snippets.

@riston
Created February 19, 2015 17:10
Show Gist options
  • Save riston/a46ef49b060882880df4 to your computer and use it in GitHub Desktop.
Save riston/a46ef49b060882880df4 to your computer and use it in GitHub Desktop.
Database service module for Node.js
var config = require("config");
var pg = require("pg");
var PromiseB = require("bluebird");
PromiseB.promisifyAll(pg);
// To prevent data loss handle bigint as string
// https://github.com/brianc/node-postgres/pull/353
pg.defaults.parseInt8 = false;
var DbService = {
getConnection: function () {
var url = config.get("DB.connString");
var close;
return pg.connectAsync(url)
.spread(function (client, done)
{
close = done;
return client;
})
.disposer(function (client)
{
if (close) {
close(client);
}
});
},
query: function (query, parameters) {
return PromiseB.using(this.getConnection(), function (connection)
{
// Don't leak the `connection` variable anywhere from here
// it is only guaranteed to be open while the promise returned from
// this callback is still pending
return connection.queryAsync(query, parameters);
}).get("rows");
}
};
module.exports = DbService;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment