Created
November 8, 2017 11:55
-
-
Save parthghiya/3f1c3428b1cf3cc6d76ddd18b4521e03 to your computer and use it in GitHub Desktop.
API Aggragation sample in microservices
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
/* | |
* Parses the request and dispatches multiple concurrent requests to each | |
* internal endpoint. Results are aggregated and returned. | |
*/ | |
function serviceDispatch(req, res) { | |
var parsedUrl = url.parse(req.url); | |
/*Service is where we maintain the requests which we want to aggregate/ | |
Service.findOne({ url: parsedUrl.pathname }, function(err, service) { | |
if(err) { | |
logger.error(err); | |
send500(res); | |
return; | |
} | |
var authorized = roleCheck(req.context.authPayload.jwt, service); | |
if(!authorized) { | |
send401(res); | |
return; | |
} | |
// Fanout all requests to all related endpoints. | |
// Results are aggregated (more complex strategies are possible). | |
/*Calling out all requests and then aggregating them in one*/ | |
var promises = []; | |
service.endpoints.forEach(function(endpoint) { | |
logger.debug(sprintf('Dispatching request from public endpoint ' + | |
'%s to internal endpoint %s (%s)', | |
req.url, endpoint.url, endpoint.type)); | |
switch(endpoint.type) { | |
case 'http-get': | |
case 'http-post': | |
promises.push(httpPromise(req, endpoint.url, | |
endpoint.type === 'http-get')); | |
break; | |
case 'amqp': | |
promises.push(amqpPromise(req, endpoint.url)); | |
break; | |
default: | |
logger.error('Unknown endpoint type: ' + endpoint.type); | |
} | |
}); | |
/*Maintaing that queue and then playing in queue*/ | |
//Aggregation strategy for multiple endpoints. | |
Q.allSettled(promises).then(function(results) { | |
var responseData = {}; | |
results.forEach(function(result) { | |
if(result.state === 'fulfilled') { | |
responseData = _.extend(responseData, result.value); | |
} else { | |
logger.error(result.reason.message); | |
} | |
}); | |
res.setHeader('Content-Type', 'application/json'); | |
res.end(JSON.stringify(responseData)); | |
}); | |
}, 'services'); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment