osrm-backend/features/support/http.js

54 lines
2.0 KiB
JavaScript
Raw Normal View History

2016-03-04 15:11:05 -05:00
var Timeout = require('node-timeout');
var request = require('request');
module.exports = function () {
this.paramsToString = (params) => {
2016-03-29 13:35:56 -04:00
var paramString = '';
2016-03-31 15:32:44 -04:00
if (params.coordinates !== undefined) {
// FIXME this disables passing the output if its a default
// Remove after #2173 is fixed.
var outputString = (params.output && params.output !== 'json') ? ('.' + params.output) : '';
paramString = params.coordinates.join(';') + outputString;
2016-03-29 13:35:56 -04:00
delete params.coordinates;
delete params.output;
}
2016-03-25 14:58:30 -04:00
if (Object.keys(params).length) {
paramString += '?' + Object.keys(params).map(k => k + '=' + params[k]).join('&');
}
return paramString;
2016-03-04 15:11:05 -05:00
};
// FIXME this needs to be simplified!
// - remove usage of node-timeout
// - replace with node's native timout mechanism
2016-03-04 15:11:05 -05:00
this.sendRequest = (baseUri, parameters, callback) => {
2016-05-05 12:36:30 -04:00
var limit = Timeout(this.TIMEOUT, { err: { statusCode: 408 } });
2016-03-04 15:11:05 -05:00
var runRequest = (cb) => {
var params = this.paramsToString(parameters);
2016-03-25 14:58:30 -04:00
this.query = baseUri + (params.length ? '/' + params : '');
2016-03-04 15:11:05 -05:00
request(this.query, (err, res, body) => {
2016-03-04 15:11:05 -05:00
if (err && err.code === 'ECONNREFUSED') {
return cb(new Error('*** osrm-routed is not running.'));
2016-03-04 15:11:05 -05:00
} else if (err && err.statusCode === 408) {
return cb(new Error());
2016-03-04 15:11:05 -05:00
}
return cb(err, res, body);
});
};
runRequest(limit((err, res, body) => {
if (err) {
if (err.statusCode === 408)
return callback(new Error('*** osrm-routed did not respond'));
2016-03-04 15:11:05 -05:00
else if (err.code === 'ECONNREFUSED')
return callback(new Error('*** osrm-routed is not running'));
2016-03-04 15:11:05 -05:00
}
return callback(err, res, body);
}));
};
};