Skip to content

Instantly share code, notes, and snippets.

@kenming
Created July 29, 2021 13:32
Show Gist options
  • Select an option

  • Save kenming/05ede097452d5c2b707f84bf03524c65 to your computer and use it in GitHub Desktop.

Select an option

Save kenming/05ede097452d5c2b707f84bf03524c65 to your computer and use it in GitHub Desktop.
API Gateway Example by Node.js
/*
* 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');
}
@kenming
Copy link
Author

kenming commented Jul 29, 2021

A Real API Gateway Example by Node.js

一個簡單的 Node.js API Gateway 範例程式碼,它接收 HTTP 請求並將其轉發到內部端點,並在此過程中使用 JWT (JSON Web Token) 進行身份驗證。

  1. 當收到請求時,會使用 serviceDispatch() 函數對其進行處理,該函數嘗試匹配來自相關服務的請求數據。
  2. Service.endpoints.forEach() 函數然後向內部網絡中的已知端點發送請求—換句話說,這兩個函數構成了 API Gateway 資料流的第一次處理。
  3. 在此之後,API 使用 result() 函數來聚合返回給 Gateway 的回應 (response),此時,適當的回應被傳送給請求它的用戶。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment