module.exports.endpoint = async function (request, response){
var got = require("got");
const queryString = require('query-string');
var mySec = process.env.bkey
const uri = "http://dev.virtualearth.net/REST/v1/Routes/Driving"
let queryStart = -1;
let url = request.url;
let parameters;
if ((queryStart = request.url.indexOf('?')) > -1) {
url = url.substring(0, queryStart + 1);
parameters = queryString.parse(request.url.substring(queryStart + 1));
}
var bingURL = uri + "?wp.1=" + parameters.wp1 + "&wp.2=" + parameters.wp2 + "&optmz=timeWithTraffic&ra=routeSummariesOnly&du=km&o=json&key=" + mySec;
console.log("URL to get is: " + bingURL);
var result = got.get(bingURL).then(result => {
console.log("Got a valid response: " + JSON.stringify(JSON.parse(result.body).resourceSets[0].resources[0].travelDurationTraffic));
var obj = {};
obj.minutes = Math.round(JSON.parse(result.body).resourceSets[0].resources[0].travelDurationTraffic / 60);
function convertMinsToHrsMins(mins) {
let h = Math.floor(mins / 60);
let m = mins % 60;
h = h < 10 ? '0' + h : h;
m = m < 10 ? '0' + m : m;
return `${h}:${m}`;
}
var objTime = {
"travelTime": convertMinsToHrsMins(obj.minutes)
}
response.end(JSON.stringify(objTime));
}).catch((err) => {
console.log(err);
response.end(err);
});
}