Skip to content

Instantly share code, notes, and snippets.

@myndzi
Created June 24, 2014 18:51
Show Gist options
  • Save myndzi/a2b91915cd17a7cf09b6 to your computer and use it in GitHub Desktop.
Save myndzi/a2b91915cd17a7cf09b6 to your computer and use it in GitHub Desktop.
var pg = require('pg');
var request = require('request');
var Promise = require('bluebird'); // version 2.0!
// pg interface is a bit awkward to promisify
var connect = Promise.promisify(pg.connect, pg);
pg.connect = function (connString) {
return connect(connString).spread(function (client, done) {
client.done = done;
Promise.promisify(client, { suffix: '$' });
});
}
var request$ = Promise.promisify(request);
function getUrl(location) {
return 'https://maps.googleapis.com/maps/api/geocode/json?address=' + location.address + ', ' + location.city + ', ' + location.state + ' ' + location.zip_code;
}
var count = 0;
pg.connect(connString)
.then(function (client) {
return client.query$('SELECT id, address, city, state, zip_code FROM companies WHERE pos IS NULL')
.reduce(function (ignore, company) { // using reduce to execute requests only one at a time
return request(getUrl(company))
.spread(function (res, body) {
var location = body.results[0].geometry.location;
return client.query$(
'UPDATE companies SET pos = point($1, $2) WHERE id = $3',
[ location.lng, location.lat, company.id ]
);
})
.catch(function (err) {
console.error("Error fetching data for %s: %s", company, err);
});
});
}).catch(function (err) {
console.error("Error: %s", err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment