UNPKG

@magnetarjs/core

Version:
72 lines (71 loc) 2.88 kB
import { isCacheStoreAddedResult } from '@magnetarjs/types'; /** * Executes given function array with given args-array deconstructed, it will always use replace the first param with whatever the response of each function was. */ export function executeOnFns(params) { const { modifyReadResultFns, cacheStoreFns, payload, docMetaData, eventFns, eventContext } = params; let newPayload = payload; let shouldAbort = false; // Execute 'before' event functions (sync, fire-and-forget for async) if (eventFns && eventContext) { const eventPayload = { payload: newPayload, actionName: 'stream', storeName: eventContext.storeName, collectionPath: eventContext.collectionPath, docId: eventContext.docId, path: eventContext.path, pluginModuleConfig: eventContext.pluginModuleConfig, streamEvent: eventContext.streamEvent, abort: () => (shouldAbort = true), current: undefined, diffApplied: 'na', }; for (const fn of eventFns.before) { if (shouldAbort) break; fn(eventPayload); // fire-and-forget: don't await } } if (shouldAbort) return undefined; for (const fn of modifyReadResultFns) { // we only want to execute these when there is a payload if (newPayload) newPayload = fn(newPayload, docMetaData); } let cacheStoreResult; for (const fn of cacheStoreFns) { // we only want to execute these always, regardless wether or not there's a payload const intermediaryResult = fn(newPayload, docMetaData); if (isCacheStoreAddedResult(intermediaryResult)) { cacheStoreResult = intermediaryResult; newPayload = intermediaryResult.current; } else { newPayload = intermediaryResult; } } // Execute 'success' event functions (sync, fire-and-forget for async) if (eventFns && eventContext) { const eventPayload = { payload: newPayload, result: newPayload, actionName: 'stream', storeName: eventContext.storeName, collectionPath: eventContext.collectionPath, docId: eventContext.docId, path: eventContext.path, pluginModuleConfig: eventContext.pluginModuleConfig, streamEvent: eventContext.streamEvent, // eslint-disable-next-line @typescript-eslint/no-empty-function abort: () => { }, // no-op for stream events current: cacheStoreResult?.current, diffApplied: cacheStoreResult?.diffApplied || 'na', }; for (const fn of eventFns.success) { fn(eventPayload); // fire-and-forget: don't await } } return newPayload; }