Projekt

Obecné

Profil

Stáhnout (1.32 KB) Statistiky
| Větev: | Revize:
1
import compose from './compose'
2

    
3
/**
4
 * Creates a store enhancer that applies middleware to the dispatch method
5
 * of the Redux store. This is handy for a variety of tasks, such as expressing
6
 * asynchronous actions in a concise manner, or logging every action payload.
7
 *
8
 * See `redux-thunk` package as an example of the Redux middleware.
9
 *
10
 * Because middleware is potentially asynchronous, this should be the first
11
 * store enhancer in the composition chain.
12
 *
13
 * Note that each middleware will be given the `dispatch` and `getState` functions
14
 * as named arguments.
15
 *
16
 * @param {...Function} middlewares The middleware chain to be applied.
17
 * @returns {Function} A store enhancer applying the middleware.
18
 */
19
export default function applyMiddleware(...middlewares) {
20
  return createStore => (...args) => {
21
    const store = createStore(...args)
22
    let dispatch = () => {
23
      throw new Error(
24
        'Dispatching while constructing your middleware is not allowed. ' +
25
          'Other middleware would not be applied to this dispatch.'
26
      )
27
    }
28

    
29
    const middlewareAPI = {
30
      getState: store.getState,
31
      dispatch: (...args) => dispatch(...args)
32
    }
33
    const chain = middlewares.map(middleware => middleware(middlewareAPI))
34
    dispatch = compose(...chain)(store.dispatch)
35

    
36
    return {
37
      ...store,
38
      dispatch
39
    }
40
  }
41
}
(1-1/6)