UNPKG

1.73 kBJavaScriptView Raw
1import { is, check, uid as nextSagaId, wrapSagaDispatch, noop, log } from './utils'
2import proc from './proc'
3
4const RUN_SAGA_SIGNATURE = 'runSaga(storeInterface, saga, ...args)'
5const NON_GENERATOR_ERR = `${RUN_SAGA_SIGNATURE}: saga argument must be a Generator function!`
6
7export function runSaga(storeInterface, saga, ...args) {
8 let iterator
9
10 if (is.iterator(storeInterface)) {
11 if (process.env.NODE_ENV === 'development') {
12 log('warn', `runSaga(iterator, storeInterface) has been deprecated in favor of ${RUN_SAGA_SIGNATURE}`)
13 }
14 iterator = storeInterface
15 storeInterface = saga
16 } else {
17 check(saga, is.func, NON_GENERATOR_ERR)
18 iterator = saga(...args)
19 check(iterator, is.iterator, NON_GENERATOR_ERR)
20 }
21
22 const { subscribe, dispatch, getState, context, sagaMonitor, logger, onError } = storeInterface
23
24 const effectId = nextSagaId()
25
26 if (sagaMonitor) {
27 // monitors are expected to have a certain interface, let's fill-in any missing ones
28 sagaMonitor.effectTriggered = sagaMonitor.effectTriggered || noop
29 sagaMonitor.effectResolved = sagaMonitor.effectResolved || noop
30 sagaMonitor.effectRejected = sagaMonitor.effectRejected || noop
31 sagaMonitor.effectCancelled = sagaMonitor.effectCancelled || noop
32 sagaMonitor.actionDispatched = sagaMonitor.actionDispatched || noop
33
34 sagaMonitor.effectTriggered({ effectId, root: true, parentEffectId: 0, effect: { root: true, saga, args } })
35 }
36
37 const task = proc(
38 iterator,
39 subscribe,
40 wrapSagaDispatch(dispatch),
41 getState,
42 context,
43 { sagaMonitor, logger, onError },
44 effectId,
45 saga.name,
46 )
47
48 if (sagaMonitor) {
49 sagaMonitor.effectResolved(effectId, task)
50 }
51
52 return task
53}