1 | import { is, check, object, createSetContextWarning } from './utils'
|
2 | import { emitter } from './channel'
|
3 | import { ident } from './utils'
|
4 | import { runSaga } from './runSaga'
|
5 |
|
6 | export default function sagaMiddlewareFactory({ context = {}, ...options } = {}) {
|
7 | const { sagaMonitor, logger, onError } = options
|
8 |
|
9 | if (is.func(options)) {
|
10 | if (process.env.NODE_ENV === 'production') {
|
11 | throw new Error('Saga middleware no longer accept Generator functions. Use sagaMiddleware.run instead')
|
12 | } else {
|
13 | throw new Error(
|
14 | `You passed a function to the Saga middleware. You are likely trying to start a\
|
15 | Saga by directly passing it to the middleware. This is no longer possible starting from 0.10.0.\
|
16 | To run a Saga, you must do it dynamically AFTER mounting the middleware into the store.
|
17 | Example:
|
18 | import createSagaMiddleware from 'redux-saga'
|
19 | ... other imports
|
20 |
|
21 | const sagaMiddleware = createSagaMiddleware()
|
22 | const store = createStore(reducer, applyMiddleware(sagaMiddleware))
|
23 | sagaMiddleware.run(saga, ...args)
|
24 | `,
|
25 | )
|
26 | }
|
27 | }
|
28 |
|
29 | if (logger && !is.func(logger)) {
|
30 | throw new Error('`options.logger` passed to the Saga middleware is not a function!')
|
31 | }
|
32 |
|
33 | if (process.env.NODE_ENV === 'development' && options.onerror) {
|
34 | throw new Error('`options.onerror` was removed. Use `options.onError` instead.')
|
35 | }
|
36 |
|
37 | if (onError && !is.func(onError)) {
|
38 | throw new Error('`options.onError` passed to the Saga middleware is not a function!')
|
39 | }
|
40 |
|
41 | if (options.emitter && !is.func(options.emitter)) {
|
42 | throw new Error('`options.emitter` passed to the Saga middleware is not a function!')
|
43 | }
|
44 |
|
45 | function sagaMiddleware({ getState, dispatch }) {
|
46 | const sagaEmitter = emitter()
|
47 | sagaEmitter.emit = (options.emitter || ident)(sagaEmitter.emit)
|
48 |
|
49 | sagaMiddleware.run = runSaga.bind(null, {
|
50 | context,
|
51 | subscribe: sagaEmitter.subscribe,
|
52 | dispatch,
|
53 | getState,
|
54 | sagaMonitor,
|
55 | logger,
|
56 | onError,
|
57 | })
|
58 |
|
59 | return next => action => {
|
60 | if (sagaMonitor && sagaMonitor.actionDispatched) {
|
61 | sagaMonitor.actionDispatched(action)
|
62 | }
|
63 | const result = next(action)
|
64 | sagaEmitter.emit(action)
|
65 | return result
|
66 | }
|
67 | }
|
68 |
|
69 | sagaMiddleware.run = () => {
|
70 | throw new Error('Before running a Saga, you must mount the Saga middleware on the Store using applyMiddleware')
|
71 | }
|
72 |
|
73 | sagaMiddleware.setContext = props => {
|
74 | check(props, is.object, createSetContextWarning('sagaMiddleware', props))
|
75 | object.assign(context, props)
|
76 | }
|
77 |
|
78 | return sagaMiddleware
|
79 | }
|