reducerInjectors.js 904 Bytes
Newer Older
Julien Benchetrit's avatar
Julien Benchetrit committed
1 2 3 4
import invariant from 'invariant';
import { isEmpty, isFunction, isString } from 'lodash';

import createReducer from '../reducers';
dengxiaofeng's avatar
dengxiaofeng committed
5
import checkStore from './checkStore';
Julien Benchetrit's avatar
Julien Benchetrit committed
6 7 8 9 10 11 12

export function injectReducerFactory(store, isValid) {
  return function injectReducer(key, reducer) {
    if (!isValid) checkStore(store);

    invariant(
      isString(key) && !isEmpty(key) && isFunction(reducer),
dengxiaofeng's avatar
dengxiaofeng committed
13
      '(src/utils...) injectReducer: Expected `reducer` to be a reducer function',
Julien Benchetrit's avatar
Julien Benchetrit committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
    );

    if (
      Reflect.has(store.injectedReducers, key) &&
      store.injectedReducers[key] === reducer
    )
      return;

    store.injectedReducers[key] = reducer; // eslint-disable-line no-param-reassign
    store.replaceReducer(createReducer(store.injectedReducers));
  };
}

export default function getInjectors(store) {
  checkStore(store);

  return {
    injectReducer: injectReducerFactory(store, true),
  };
}