UNPKG

1.55 kBJavaScriptView Raw
1'use strict';
2
3const { asyncParamApiCallback, nameRetriever, toFlatArray } = require('../../utils');
4
5module.exports = ({ reactions = {}, identity = {} }, customApiBuilder = saga => saga, { Saga }) => Object.entries(reactions).map(([fullName, reaction]) => {
6 const [context, aggregate, name] = nameRetriever.event(fullName);
7
8 let identifier = identity[fullName];
9 let sagaFunction;
10 let shouldHandle;
11
12 const sagaSettings = {
13 name,
14 context,
15 aggregate,
16 };
17
18 reaction = toFlatArray(reaction);
19
20 reaction.forEach((item) => {
21 if (!item)
22 throw new Error('No saga function specified');
23
24 if (item.settings)
25 return Object.assign(sagaSettings, item.settings);
26
27 if (item.useAsId) {
28 identifier = item.useAsId;
29 return null;
30 }
31
32 if (item.shouldHandle) {
33 shouldHandle = asyncParamApiCallback(item.shouldHandle, customApiBuilder, 'evt', 'saga');
34 return null;
35 }
36
37 if (typeof item === 'function') {
38 sagaFunction = (event, saga, callback) => Promise.resolve(item(event, saga, customApiBuilder(event, saga))).then(() => saga.commit(callback), callback);
39 return null;
40 }
41 return null;
42 });
43
44 if (!sagaFunction)
45 throw new Error(`No saga function specified for event ${fullName}`);
46
47 if (identifier && typeof identifier === 'string')
48 sagaSettings.id = identifier;
49
50 const sagaDefinition = new Saga(sagaSettings, sagaFunction);
51
52 if (identifier && typeof identifier === 'function')
53 sagaDefinition.useAsId(identifier);
54
55 if (shouldHandle)
56 sagaDefinition.defineShouldHandle(shouldHandle);
57
58 return sagaDefinition;
59});