Created
June 19, 2014 22:46
-
-
Save heymatthew/53aa39b86dfeffabbdef to your computer and use it in GitHub Desktop.
Simple Reusable Proxy with Partial Application
This file contains 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 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