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), {}); }); }