2018-08-31 04:36:26 -05:00
|
|
|
const bodyParser = require('body-parser');
|
|
|
|
|
2018-12-23 07:57:32 -06:00
|
|
|
import {sendActionToService} from '@truss/comm';
|
2018-08-31 04:36:26 -05:00
|
|
|
|
2018-12-23 07:57:32 -06:00
|
|
|
const debug = require('debug')('truss:gateway:listener');
|
2018-08-31 04:36:26 -05:00
|
|
|
|
|
|
|
const parser = bodyParser.json();
|
|
|
|
|
2018-09-08 22:54:33 -05:00
|
|
|
export default function(serviceMap, req, res) { parser(req, res, () => {
|
2018-08-31 04:36:26 -05:00
|
|
|
debug(`HTTP ${req.method} ${req.url}`);
|
|
|
|
// map to action
|
2018-09-02 07:25:51 -05:00
|
|
|
const action = {type: undefined, payload: {url: req.url}};
|
2018-08-31 04:36:26 -05:00
|
|
|
switch (req.method) {
|
|
|
|
case 'POST':
|
2018-12-23 07:57:32 -06:00
|
|
|
// truss action
|
|
|
|
if (req.url.startsWith('/truss/action/')) {
|
|
|
|
action.type = req.url.substr('/truss/action/'.length);
|
|
|
|
}
|
|
|
|
// truss/http-post
|
|
|
|
else {
|
|
|
|
action.type = 'truss/http-post';
|
|
|
|
}
|
2018-08-31 04:36:26 -05:00
|
|
|
action.payload.body = req.body;
|
|
|
|
break;
|
|
|
|
default:
|
2018-12-23 07:57:32 -06:00
|
|
|
// truss/http-(get|delete|...)
|
2018-08-31 04:36:26 -05:00
|
|
|
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]
|
2018-09-08 22:54:33 -05:00
|
|
|
).then(({status, headers, html}) => {
|
2018-08-31 04:36:26 -05:00
|
|
|
// deliver
|
2018-09-08 22:54:33 -05:00
|
|
|
res.writeHead(status || 200, headers);
|
2018-08-31 04:36:26 -05:00
|
|
|
res.end(html);
|
|
|
|
}).catch(console.error);
|
|
|
|
})};
|