Skip to content

Instantly share code, notes, and snippets.

@heymatthew
Created June 19, 2014 22:46
Show Gist options
  • Save heymatthew/53aa39b86dfeffabbdef to your computer and use it in GitHub Desktop.
Save heymatthew/53aa39b86dfeffabbdef to your computer and use it in GitHub Desktop.
Simple Reusable Proxy with Partial Application
var express = require('express');
var extend = require('extend');
var q = require('q');
var request = q.denodeify( require('request') );
var makeRequester = function makeRequester(opts) {
return function requester(path) {
var retrieveResponse =
request({
'strictSSL': opts.selfsigned !== true, // for snakeoil certs
'uri': opts.url + path,
})
.then(function transform(response) {
return {
'meta': response[0],
'body': response[1],
};
})
;
return retrieveResponse;
};
};
var esRequest = makeRequester({
'url' : 'https://localhost:9200',
'selfsigned': true,
});
var app = express();
var scrubNodesData = function scrubNodesData(data) {
var cleanData = extend({}, data); // shallow
cleanData.nodes = Object.keys(cleanData.nodes).reduce(
function scrub(accumulator, nodeKey) {
accumulator[nodeKey] = {
'name': data.nodes[nodeKey].name,
'version': data.nodes[nodeKey].version,
};
return accumulator;
},
{}
);
return cleanData;
};
app.get('*', function(req,res) {
esRequest(req.path)
.then(function(proxyResponse) {
console.log(req.path);
if ( req.path.match(/_nodes/) ) {
var data = scrubNodesData( JSON.parse(proxyResponse.body) );
res.send(proxyResponse.meta.statusCode, JSON.stringify(data));
}
else {
res.send(
proxyResponse.meta.statusCode,
proxyResponse.body
);
}
})
.fail(console.error);
});
var server = app.listen(3000, function() {
console.log('Listening on port %d', server.address().port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment