2018-12-23 07:57:32 -06:00
|
|
|
const {sendActionToService} = require('@truss/comm');
|
|
|
|
|
2018-12-24 13:20:05 -06:00
|
|
|
const debug = require('debug')('truss:gateway:actions');
|
|
|
|
|
2018-12-23 07:57:32 -06:00
|
|
|
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) {
|
2018-12-24 13:20:05 -06:00
|
|
|
debug(`invoking hookFlat(${hook}(${JSON.stringify(args, null, ' ')}))...`);
|
2018-12-24 13:20:20 -06:00
|
|
|
return invokeHookFlatInternal(services, hook, args);
|
2018-12-23 07:57:32 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
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), {});
|
|
|
|
});
|
|
|
|
}
|