Created
April 4, 2016 23:03
-
-
Save fayimora/75d77834800acc967193df15434595f0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var distance = require('google-distance'); | |
var _ = require('lodash'); | |
module.exports = function (pubnub) { | |
pubnub.subscribe({ | |
channel: "dispatch", | |
message: onNewDispatch | |
}); | |
function onNewDispatch(message) { | |
const payload = JSON.parse(message); | |
var store = findClosestStore(payload.stores); | |
var rider = findRider(store); | |
var riderMessage = { | |
"delivery_id": payload.delivery_id, | |
"store": store | |
}; | |
pubnub.publish({ | |
channel: "riders."+rider.id | |
message: riderMessage, | |
callback: function (res) { | |
console.log("Succesfully dispatched delivery "+payload.delivery_id+" to "+rider.id); | |
} | |
}); | |
} | |
function distanceBetween(origin, destination, callback) { | |
var distanceInMetres; | |
distance.get( | |
{origin: origin, destination: destination}, | |
function (err, data) { | |
if(err) return console.log(err); | |
distanceInMetres = data.distanceValue; | |
} | |
); | |
return distanceInMetres; | |
} | |
function findStore(stores, destination) { | |
// here we want to find the closest store | |
stores = _.map(stores, function (store) { | |
store["distance"] = distanceBetween(store.address, destination); | |
return store; | |
}); | |
stores = _.sortBy(stores, 'distance'); | |
} | |
function findRider(store) { | |
var riderIds; | |
pubnub.here_now({ | |
channel: 'riders.*', | |
callback: function (m) { | |
riderIds = m.uuids; | |
} | |
}); | |
} | |
}; |
bigmeech
commented
Apr 5, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment