Created
July 29, 2021 13:32
-
-
Save kenming/05ede097452d5c2b707f84bf03524c65 to your computer and use it in GitHub Desktop.
API Gateway Example by Node.js
This file contains hidden or 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.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). | |
| 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); | |
| } | |
| }); | |
| //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'); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A Real API Gateway Example by Node.js
一個簡單的 Node.js API Gateway 範例程式碼,它接收 HTTP 請求並將其轉發到內部端點,並在此過程中使用 JWT (JSON Web Token) 進行身份驗證。