Skip to content

Instantly share code, notes, and snippets.

@gojko
Created January 13, 2017 22:32
Show Gist options
  • Save gojko/d2c1cf40ce62b464154c8d86ecc31fb1 to your computer and use it in GitHub Desktop.
Save gojko/d2c1cf40ce62b464154c8d86ecc31fb1 to your computer and use it in GitHub Desktop.
example rewriting pg access to promises
/*global require, module*/
var pg = require('pg'),
API = require('claudia-api-builder'),
api = new API();
module.exports = api;
// do this once, so it does not reconnect for each request.
// may need to handle reconnecting somehow inside a request?
var conString = process.env.DATABASE_URL || "postgres://<user>:<pass>@<connection>:5432/<db>";
var client = new pg.Client(conString);
client.connect();
api.get('/', function (request) {
console.log("Inside the Get Function");
// return is critical here, see https://claudiajs.com/tutorials/external-services.html
return new Promise((resolve, reject) => {
console.log("Inside the Promise");
client.query('SELECT * FROM public.account ORDER BY id ASC;', function(err, result) {
console.log("Inside the Query Result");
if(err) {
return reject(err);
}
console.log(">>> successful query. jsonResult: " + jsonResult);
return resolve(result); // jSON is the default data type, so no need to stringify
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment