ironbar/services/gateway/actions.js
2018-12-24 13:20:20 -06:00

38 lines
1.3 KiB
JavaScript

const {sendActionToService} = require('@truss/comm');
const debug = require('debug')('truss:gateway:actions');
module.exports = (serviceMap) => ({
'truss/hook-services': ({payload: {hook, args}}) => {
if (!(hook in serviceMap.hooks)) { return []; }
return serviceMap.hooks[hook];
},
'truss/invoke': ({payload: {hook, args}}) => {
if (!(hook in serviceMap.hooks)) { return {}; }
return invokeHook(serviceMap.hooks[hook], hook, args);
},
'truss/invoke-flat': ({payload: {hook, args}}) => {
if (!(hook in serviceMap.hooks)) { return []; }
return invokeHookFlat(serviceMap.hooks[hook], hook, args);
},
});
function invokeHookFlat(services, hook, args) {
debug(`invoking hookFlat(${hook}(${JSON.stringify(args, null, ' ')}))...`);
return invokeHookFlatInternal(services, hook, args);
}
function invokeHookFlatInternal(services, hook, args) {
const action = {type: 'truss/hook', payload: {hook, args}};
return Promise.all(services.map((service) => {
return sendActionToService(action, service);
}));
}
function invokeHook(services, hook, args) {
debug(`invoking hook ${hook}(${JSON.stringify(args, null, ' ')})...`);
return invokeHookFlatInternal(services, hook, args).then((result) => {
return result.reduce((l, r, i) => (l[services[i]] = r, l), {});
});
}