ironbar/services/gateway/listener.js
2018-08-31 04:36:26 -05:00

58 lines
1.3 KiB
JavaScript

const bodyParser = require('body-parser');
const debug = require('debug')('truss:gateway:listener');
const {sendActionToService} = require('@truss/truss');
const parser = bodyParser.json();
module.exports = function(serviceMap, req, res) { parser(req, res, () => {
debug(`HTTP ${req.method} ${req.url}`);
// map to action
const action = {payload: {url: req.url}};
switch (req.method) {
case 'POST':
action.type = req.url.startsWith('/truss/action/') ?
req.url.substr('/truss/action/'.length): 'truss/http-post'
;
action.payload.body = req.body;
break;
default:
// truss/http-(GET|DELETE|...)
action.type = `truss/http-${req.method.toLowerCase()}`;
action.payload.headers = req.headers;
break;
}
// listeners...
for (service of serviceMap.listeners[action.type] || []) {
sendActionToService(action, service).done();
}
// executor
if (!(action.type in serviceMap.executors)) {
debug(`No executor for ${action.type}!`);
res.writeHead(501);
res.end(
'<!DOCTYPE html><html><body><h1>501 Not Implemented</h1></body></html>'
);
return;
}
sendActionToService(
action, serviceMap.executors[action.type]
).then(({status, html}) => {
// deliver
res.writeHead(status || 200);
res.end(html);
}).catch(console.error);
})};