Example #1
0
  this.$get = function ($injector) {
    var store = undefined,
        resolvedMiddleware = [];

    for (var _iterator = _middlewares, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
      var _ref;

      if (_isArray) {
        if (_i >= _iterator.length) break;
        _ref = _iterator[_i++];
      } else {
        _i = _iterator.next();
        if (_i.done) break;
        _ref = _i.value;
      }

      var middleware = _ref;

      if (typeof middleware === 'string') {
        resolvedMiddleware.push($injector.get(middleware));
      } else {
        resolvedMiddleware.push(middleware);
      }
    }

    var finalCreateStore = _storeEnhancers ? _redux.compose.apply(undefined, _storeEnhancers)(_redux.createStore) : _redux.createStore;

    //digestMiddleware needs to be the last one.
    resolvedMiddleware.push((0, _digestMiddleware2.default)($injector.get('$rootScope')));

    store = _initialState ? _redux.applyMiddleware.apply(undefined, resolvedMiddleware)(finalCreateStore)(_reducer, _initialState) : _redux.applyMiddleware.apply(undefined, resolvedMiddleware)(finalCreateStore)(_reducer);

    return (0, _lodash2.default)({}, store, { connect: (0, _connector2.default)(store) });
  };
Example #2
0
const configureStore = (cozyClient, persistedState) => {
  // Enable Redux dev tools
  const composeEnhancers =
    (__DEVELOPMENT__ && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) || compose

  // reducers
  const reducers = [appReducers, persistedState]

  // middlewares
  const middlewares = [thunkMiddleware, cozyMiddleware(cozyClient)]
  if (shouldEnableTracking() && getTracker()) {
    middlewares.push(createTrackerMiddleware())
  }
  if (flag('logs') && __DEVELOPMENT__) { // eslint-disable-line
    // must be the last middleware in chain https://git.io/vHQpt
    const loggerMiddleware = createLogger()
    middlewares.push(loggerMiddleware)
  }
  if (isReporterEnabled()) {
    middlewares.push(getReporterMiddleware())
  }

  const store = createStore(
    ...reducers,
    composeEnhancers(applyMiddleware.apply(null, middlewares))
  )

  cozyClient.attachStore(store)

  return store
}
Example #3
0
export default function configureStore(initialState, client, appendage = []) {
  const reducer = combineReducers(reducers);
  const middlewares = applyMiddleware.apply(null, [
    thunkMiddleware,
    apiMiddleware(client),
    promiseMiddleware,
    normalizeMiddleware,
    injectReplaceMiddleware,
    injectAppendMiddleware,
    injectRelationMiddleware,
    logger
  ].concat(appendage));

  let createStoreWithMiddleware = middlewares(createStore);

  if (__CLIENT__ && __DEVELOPMENT__ && __DEVTOOLS__) {
    const { devTools, persistState } = require('redux-devtools');
    createStoreWithMiddleware = compose(
      middlewares,
      devTools(),
      persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))
    )(createStore);
  }

  return createStoreWithMiddleware(reducer, initialState);
}
Example #4
0
export function createStore(state) {
  return reduxCreateStore(
    reducers,
    state,
    applyMiddleware.apply(null, middlewares)
  );
}
export default function configureStore() {
  // On the client, we pass in an array of sockets.
  // We will create one middleware step for each one.
  // When actions are dispatched, each middleware will check its middleware.
  // if the action has specified its namespace as a remote, the socket will
  // emit an action on that socket with the action data, along with some
  // mixed-in extras (like the current user's auth data.)


  let middlewares = [];
  middlewares.push( thunkMiddleware );

  const store = createStore(
    rootReducer,
    compose(
      applyMiddleware.apply(this, middlewares),
      DevTools.instrument()
    )
  );

  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    module.hot.accept('../reducers', () => {
      const nextRootReducer = require('../reducers');
      store.replaceReducer(nextRootReducer);
    });
  }

  // Allow direct access to the store, for debugging/testing
  window.__store = store;

  return store
}
Example #6
0
    match({routes, location}, (err, redirectLocation, renderProps) => {
        if (err) {
            return res.status(500).send(err.message)
        }

        if (!renderProps) {
            return res.status(404).send('not found')
        }

        const store = compose(
            applyMiddleware.apply(this, middleware)
        )(createStore)(rootReducer);

        // render the component to string
        const initialView = renderToString(
            <div>
                <Provider store={store}>
                    { <RoutingContext {...renderProps} /> }
                </Provider>
            </div>
        );

        const initialState = store.getState();

        const assets = require('../../stats.json');

        res.render('index', {
            html: initialView,
            assets,
            initialState
        })
    })
Example #7
0
export function createApolloStore(_a) {
    var _b = _a === void 0 ? {} : _a, _c = _b.reduxRootKey, reduxRootKey = _c === void 0 ? 'apollo' : _c, initialState = _b.initialState, _d = _b.config, config = _d === void 0 ? {} : _d, _e = _b.reportCrashes, reportCrashes = _e === void 0 ? true : _e, logger = _b.logger;
    var enhancers = [];
    var middlewares = [];
    if (reportCrashes) {
        middlewares.push(crashReporter);
    }
    if (logger) {
        middlewares.push(logger);
    }
    if (middlewares.length > 0) {
        enhancers.push(applyMiddleware.apply(void 0, middlewares));
    }
    if (typeof window !== 'undefined') {
        var anyWindow = window;
        if (anyWindow.devToolsExtension) {
            enhancers.push(anyWindow.devToolsExtension());
        }
    }
    var compose = reduxCompose;
    if (initialState && initialState[reduxRootKey] && initialState[reduxRootKey]['queries']) {
        throw new Error('Apollo initial state may not contain queries, only data');
    }
    if (initialState && initialState[reduxRootKey] && initialState[reduxRootKey]['mutations']) {
        throw new Error('Apollo initial state may not contain mutations, only data');
    }
    return createStore(combineReducers((_f = {}, _f[reduxRootKey] = createApolloReducer(config), _f)), initialState, compose.apply(void 0, enhancers));
    var _f;
}
  return function (clazz) {
    var reduxRouterMiddleware = (0, _reactRouterRedux.routerMiddleware)();
    var middleware = [reduxRouterMiddleware];

    var wrappderCreateStoreFn = _redux.applyMiddleware.apply(undefined, middleware)(_redux.createStore);

    store = wrappderCreateStoreFn((0, _redux.combineReducers)(reducersFns));
    return clazz;
  };
export default function configureStore() {
  let middlewares = [];
  middlewares.push( thunkMiddleware );

  return createStore(
    rootReducer,
    applyMiddleware.apply(null, middlewares)
  );
}
Example #10
0
function _getMiddleware() {
    var middleware = [
        promise_middleware_1.default,
        redux_thunk_1.default
    ];
    if (__DEV__) {
        middleware = middleware.slice();
    }
    return redux_1.applyMiddleware.apply(void 0, middleware);
}
Example #11
0
    createDebugStore: function(reducer, initialState, userMiddlewares, enhancer) {
        let finalCreateStore;
        if (__DEVTOOLS__ && urlQuery.debug) {
            let logger = require('redux-logger')();
            let immutable = require('redux-immutable-state-invariant')();
            let middlewares = (userMiddlewares || []).concat([immutable, thunkMiddleware, logger]);
            const {persistState} = require('redux-devtools');
            const DevTools = require('../components/development/DevTools');

            finalCreateStore = compose(
              applyMiddleware.apply(null, middlewares),
            window.devToolsExtension ? window.devToolsExtension() : DevTools.instrument(),
              persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))
          )(createStore);
        } else {
            let middlewares = (userMiddlewares || []).concat([thunkMiddleware]);
            finalCreateStore = applyMiddleware.apply(null, middlewares)(createStore);
        }
        return finalCreateStore(reducer, initialState, enhancer);
    }
export default function createEnhancedStore(persistStateConfig = {}) {
  const middlewares = [
    thunkMiddleware,
  ];

  const store = createStore(
    reducer,
    compose(
      persistState(persistStateConfig),
      applyMiddleware.apply(this, middlewares)
    )
  );

  return store;
}
Example #13
0
  return function mockStore(_getState, expectedActions, done) {
    if (!expectedActions) {
      throw new Error('expectedActions should be an expected action or an array of actions.');
    } else if (!Array.isArray(expectedActions)) {
      expectedActions = [expectedActions];
    }

    if (typeof done !== 'undefined' && typeof done !== 'function') {
      throw new Error('done should either be undefined or function.');
    }

    function mockStoreWithoutMiddleware() {
      var self = {
        getState: function getState() {
          return typeof _getState === 'function' ? _getState() : _getState;
        },

        dispatch: function dispatch(action) {
          if (action instanceof Function) {
            return action(self);
          }

          var expectedAction = expectedActions.shift();

          try {
            (0, _expect2['default'])(action).toEqual(expectedAction);
            if (done && !expectedActions.length) {
              done();
            }
            return action;
          } catch (e) {
            if (done) {
              done(e);
            } else {
              throw e;
            }
          }
        }
      };

      return self;
    }

    var mockStoreWithMiddleware = _redux.applyMiddleware.apply(undefined, _toConsumableArray(middlewares))(mockStoreWithoutMiddleware);

    return mockStoreWithMiddleware();
  };
Example #14
0
export default function configureStore(
  data,
  reducersMap,
  middlewares = [],
  enhancers = [],
) {
  let store = createStore(
    combinedReducers(reducersMap),
    data,
    compose.apply(
      null,
      [applyMiddleware.apply(null, middlewares)].concat(
        enhancers.map(enhancer => enhancer()),
      ),
    ),
  );
  return store;
}
var configureStore = function (_a) {
    var reducer = _a.reducer, devMode = _a.devMode, throttle = _a.throttle;
    var middlewares = [redux_thunk_1.default];
    if (devMode) {
        var logger = createLogger();
        middlewares.push(logger);
    }
    else {
        process.env.NODE_ENV = 'production';
    }
    if (throttle) {
        var toThrottle = Object.keys(throttle);
        toThrottle.forEach(function (action) {
            middlewares.push(redux_throttle_actions_1.default([].concat(action), throttle[action]));
        });
    }
    var store = redux_1.createStore(reducer, redux_1.applyMiddleware.apply(void 0, middlewares));
    return store;
};
Example #16
0
/**
 * Initializes the store and enables hot module replacement.
 * @param {object} initialState - The initial state of the store.
 * @return {object} store - A store object.
 */
export default function configureStore(initialState) {
  const middleware = [thunkMiddleware];
  if (isDeveloping) middleware.push(createLogger());

  const store = createStore(
    rootReducer,
    initialState,
    applyMiddleware.apply(this, middleware)
  );

  if (module.hot) {
    module.hot.accept('reducers', () => {
      const nextRootReducer = require('reducers').default;
      store.replaceReducer(nextRootReducer);
    });
  }

  return store;
}
Example #17
0
export default function configureStore(initialState) {

  const middlewareArgs = false ? [thunkMiddleware] : [thunkMiddleware, createLogger()];

  const store = createStore(
    rootReducer,
    initialState,
    applyMiddleware.apply(null, middlewareArgs)
  )

  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    module.hot.accept('../reducers', () => {
      const nextRootReducer = require('../reducers').default
      store.replaceReducer(nextRootReducer)
    });
  }

  return store;
}
Example #18
0
  manager.getStore = function () {
    if (store) {
      return store;
    }

    var middlewareList = manager.middleware.list();

    var createStoreWithMiddleware = _redux.applyMiddleware.apply(undefined, _toConsumableArray(middlewareList))(_redux.createStore);
    var rootReducer = (0, _redux.combineReducers)(manager.reducer.hash());
    store = createStoreWithMiddleware(rootReducer, manager.initial.hash());

    var sagaMiddleware = manager.middleware.getSaga();
    if (sagaMiddleware) {
      var sagaList = manager.saga.list();
      var index = sagaList.length;
      while (index--) {
        sagaMiddleware.run(sagaList[index]);
      }
    }

    return store;
  };
Example #19
0
exports.initBaseApplication2 = function (initialState, reducer, mainSaga) {
    var middleware = [];
    for (var _i = 3; _i < arguments.length; _i++) {
        middleware[_i - 3] = arguments[_i];
    }
    var sagaMiddleware = redux_saga_1.default();
    var store = redux_1.createStore(reducer, initialState, redux_1.applyMiddleware.apply(void 0, [sagaMiddleware].concat(middleware)));
    sagaMiddleware.run(function () {
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, effects_1.fork(log_1.consoleLogSaga)];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, effects_1.fork(mainSaga)];
                case 2:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
    return store;
};
Example #20
0
export default ({isDebug})=> {
	const middlewares = [promiseMiddleware, thunkMiddleware, ignoreIfSame];

	if(isDebug) {
		middlewares.push(loggerMiddleware)
	}

	const finalCreateStore = compose(
		applyMiddleware.apply(null, middlewares)
	)(createStore);

	const store = finalCreateStore(reducer);

	if (isDebug || module.hot) {
		module.hot.accept('./modules/reducer', () =>
			store.replaceReducer(require('./modules/reducer'))
		);
	}

	init(store);

	return store;
}
Example #21
0
  return function mockStore() {
    var _getState = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

    function mockStoreWithoutMiddleware() {
      var actions = [];

      var self = {
        getState: function getState() {
          return isFunction(_getState) ? _getState() : _getState;
        },

        getActions: function getActions() {
          return actions;
        },

        dispatch: function dispatch(action) {
          actions.push(action);

          return action;
        },

        clearActions: function clearActions() {
          actions = [];
        },

        subscribe: function subscribe() {
          return null;
        }
      };

      return self;
    }

    var mockStoreWithMiddleware = _redux.applyMiddleware.apply(undefined, _toConsumableArray(middlewares))(mockStoreWithoutMiddleware);

    return mockStoreWithMiddleware();
  };
Example #22
0
import groupBy from 'lodash/groupBy';
import map from 'lodash/map';


import * as reducers from './reducers';
import { handlePopState } from './actions';



const middlewares = [];
middlewares.push(thunkMiddleware);
if (process.env.NODE_ENV === 'development')
    middlewares.push(createLogger());

const createStoreWithMiddleware = applyMiddleware.apply(
    undefined,
    middlewares
)(createReduxStore);

const finalReducer = combineReducers(reducers);

export function createStore(urls) {
    const store = createStoreWithMiddleware(finalReducer, {urls})
    window.addEventListener('popstate', () => handlePopState(store.dispatch, store.getState));
    return store;
};


function containsText(string, search) {
    return string.toLowerCase().indexOf(search.toLowerCase()) !== -1;
}
Example #23
0
File: index.js Project: SimplyY/dva
  // Usage:
  // app.start();
  // app.start(container);
  // app.start(container, opts);
  // app.start(opts);
  function start(container, opts = {}) {
    // If no container supplied, return jsx element.
    if (arguments.length === 0
      || (arguments.length === 1 && is.object(container))) {
      opts = container || {};
      container = null;
    } else {
      check(container, is.element, 'Container must be DOMElement.');
    }
    check(_routes, is.notUndef, 'Routes is not defined.');

    // Get sagas and reducers from model.
    let sagas = {};
    let reducers = {
      routing,
    };
    _models.forEach(model => {
      if (is.array(model.reducers)) {
        const [_reducers, enhancer] = model.reducers;
        reducers[model.namespace] = enhancer(handleActions(_reducers || {}, model.state));
      } else {
        reducers[model.namespace] = handleActions(model.reducers || {}, model.state);
      }
      sagas = { ...sagas, ...model.effects };
    });

    // Support external reducers.
    if (is.notUndef(opts.reducers)) {
      check(opts.reducers, is.object, 'Reducers must be object.');
      check(opts.reducers, optReducers => {
        for (var k in optReducers) {
          if (k in reducers) return false;
        }
        return true;
      }, 'Reducers should not be conflict with namespace in model.');
      reducers = { ...reducers, ...opts.reducers };
    }

    // Create store.
    if (is.notUndef(opts.middlewares)) {
      check(opts.middlewares, is.array, 'Middlewares must be array.')
    }
    const sagaMiddleware = createSagaMiddleware();
    const enhancer = compose(
      applyMiddleware.apply(null, [sagaMiddleware, ...(opts.middlewares || [])]),
      window.devToolsExtension ? window.devToolsExtension() : f => f
    );
    const initialState = opts.initialState || {};
    const store = app.store = createStore(
      combineReducers(reducers), initialState, enhancer
    );

    // Sync history.
    // Use try catch because it don't work in test.
    let history;
    try {
      history = syncHistoryWithStore(opts.history || hashHistory, store);
    } catch (e) {}

    // Start saga.
    sagaMiddleware.run(rootSaga);

    // Handle subscriptions.
    _models.forEach(({ subscriptions }) => {
      if (subscriptions) {
        check(subscriptions, is.array, 'Subscriptions must be an array');
        subscriptions.forEach(sub => {
          check(sub, is.func, 'Subscription must be an function');
          sub(store.dispatch, onErrorWrapper);
        });
      }
    });

    // Render and hmr.
    if (container) {
      render();
      if (opts.hmr) {
        opts.hmr(render);
      }
    } else {
      const Routes = _routes;
      return <Provider store={store}>
        <Routes history={history} />
      </Provider>;
    }

    function getWatcher(k, saga) {
      let _saga = saga;
      let _type = 'takeEvery';
      if (Array.isArray(saga)) {
        [_saga, opts] = saga;
        opts = opts || {};
        check(opts.type, is.sagaType, 'Type must be takeEvery, takeLatest or watcher');
        warn(opts.type, v => v !== 'takeEvery', 'takeEvery is the default type, no need to set it by opts');
        _type = opts.type;
      }

      function* sagaWithErrorCatch(...arg) {
        try {
          yield _saga(...arg);
        } catch (e) {
          onError(e);
        }
      }

      if (_type === 'watcher') {
        return sagaWithErrorCatch;
      } else if (_type === 'takeEvery') {
        return function*() {
          yield takeEvery(k, sagaWithErrorCatch);
        };
      } else {
        return function*() {
          yield takeLatest(k, sagaWithErrorCatch);
        };
      }
    }

    function* rootSaga() {
      for (var k in sagas) {
        if (sagas.hasOwnProperty(k)) {
          const watcher = getWatcher(k, sagas[k]);
          yield fork(watcher);
        }
      }
    }

    function render(routes) {
      const Routes = routes || _routes;
      ReactDOM.render((
        <Provider store={store}>
          <Routes history={history} />
        </Provider>
      ), container);
    }
  }
Example #24
0
import * as LocationActions from '../actions/location';
import * as TeamActions from '../actions/team';
import * as RegistrationActions from '../actions/registration';
import * as ENV from '../../env';
import { checkForUpdates } from '../utils/updater';
var HockeyApp = require('react-native-hockeyapp');

const middlewares = [thunk];
if (__DEV__) {
  // Disabling logging might help performance as XCode prints the whole objects
  // without respecing the collapsed parameter
  const logger = createLoggerMiddleware(loggerConfig)
  middlewares.push(logger);
}

const createStoreWithMiddleware = applyMiddleware.apply(this, middlewares)(createStore);
const reducer = combineReducers(reducers);
const store = createStoreWithMiddleware(reducer);

// Use different HockeyApp ID for both platforms.
const HOCKEYAPP_ID = Platform.OS === 'ios' ? ENV.HOCKEYAPP_ID : ENV.HOCKEYAPP_ID_ANDROID;

// Fetch teams & actions, check user existance
store.dispatch(CompetitionActions.fetchActionTypes());
store.dispatch(TeamActions.fetchTeams());
store.dispatch(RegistrationActions.getUser());

const RootView = React.createClass({
  componentWillMount() {
    HockeyApp.configure(HOCKEYAPP_ID, true);
  },
import { createStore, applyMiddleware, compose } from 'redux';
import { devTools, persistState } from 'redux-devtools';
import middleware from './middleware';
import reducer from './modules/reducer';
import DevTools from '../containers/DevTools';

let finalCreateStore;
if (__DEVELOPMENT__ && __DEVTOOLS__) {
  finalCreateStore = compose(
   applyMiddleware.apply(this, middleware),
   // Provides support for DevTools:
   DevTools.instrument(),
   // Optional. Lets you write ?debug_session=<key> in address bar to persist debug sessions
   persistState(getDebugSessionKey())
 )(createStore);
} else {
  finalCreateStore = compose(
   applyMiddleware.apply(this, middleware)
 )(createStore);
}

function getDebugSessionKey() {
  // You can write custom logic here!
  // By default we try to read the key from ?debug_session=<key> in the address bar
  const matches = window.location.href.match(/[?&]debug_session=([^&]+)\b/);
  return (matches && matches.length > 0)? matches[1] : null;
}

export const store = finalCreateStore(reducer);
Example #26
0
     P.S: 独立窗口可调用 window.devToolsExtension.open() */
    if (!__COMPONENT_DEVTOOLS__) {
        var devToolsExtension = window.devToolsExtension;
        if (typeof devToolsExtension === 'function') {
            enhancers.push(devToolsExtension());
        }
    }

    /* 2. 内嵌在页面中的 Redux DevTools 组件 */
    if (__COMPONENT_DEVTOOLS__) {
        var DevTools = require('COMPONENT/DevTools').default;
        enhancers.push(DevTools.instrument());
    }
}

// ======================================================
// 实例化 Store
// ======================================================
var store = exports.store = (0, _redux.createStore)((0, _REDUCER.createRootReducer)(), window.__INITIAL_STATE__ || {}, // 前后端同构(服务端渲染)数据同步
_redux.compose.apply(undefined, [_redux.applyMiddleware.apply(undefined, middlewares)].concat(enhancers)));

// ======================================================
// 配置 history 同步
// ======================================================
var history = exports.history = (0, _reactRouterRedux.syncHistoryWithStore)(browserHistory, store, { selectLocationState: function selectLocationState(state) {
        return state.router;
    } });

exports.default = store;

//# sourceMappingURL=index-compiled.js.map
Example #27
0
  // Usage:
  // app.start();
  // app.start(container);
  // app.start(container, opts);
  // app.start(opts);
  function start(container, opts = {}) {
    // If no container supplied, return jsx element.
    if (arguments.length === 0
      || (arguments.length === 1 && is.object(container))) {
      opts = container || {};
      container = null;
    } else {
      check(container, is.element, 'Container must be DOMElement.');
    }
    check(_routes, is.notUndef, 'Routes is not defined.');

    // Handle onError.
    const onError = plugin.apply('onError', function(err) {
      throw new Error(err.stack || err);
    });
    const onErrorWrapper = (err) => {
      if (err) {
        if (is.string(err)) err = new Error(err);
        onError(err);
      }
    };

    // Get sagas and reducers from model.
    let sagas = {};
    let reducers = {
      routing
    };
    _models.forEach(model => {
      if (is.array(model.reducers)) {
        const [ _reducers, enhancer ] = model.reducers;
        reducers[model.namespace] = enhancer(handleActions(_reducers || {}, model.state));
      } else {
        reducers[model.namespace] = handleActions(model.reducers || {}, model.state);
      }
      sagas = { ...sagas, ...model.effects };
    });

    // Support external reducers.
    const extraReducers = plugin.get('extraReducers');
    check(extraReducers, extraReducers => {
      for (let k in extraReducers) {
        if (k in reducers) return false;
      }
      return true;
    }, 'extraReducers should not be conflict with namespace in model.');
    reducers = { ...reducers, ...extraReducers };

    const _history = opts.history || hashHistory;

    // Create store.
    const extraMiddlewares = plugin.get('onAction');
    const reducerEnhancer = plugin.get('onReducer');
    const sagaMiddleware = createSagaMiddleware();
    const enhancer = compose(
      applyMiddleware.apply(null, [ routerMiddleware(_history), sagaMiddleware, ...(extraMiddlewares || []) ]),
      window.devToolsExtension ? window.devToolsExtension() : f => f
    );
    const initialState = opts.initialState || {};
    const store = app.store = createStore(
      reducerEnhancer(combineReducers(reducers)), initialState, enhancer
    );

    // Handle onStateChange.
    const listeners = plugin.get('onStateChange');
    for (const listener of listeners) {
      store.subscribe(listener);
    }

    // Start saga.
    sagaMiddleware.run(rootSaga);

    // Sync history.
    // Use try catch because it don't work in test.
    let history;
    try {
      history = syncHistoryWithStore(_history, store);

      const oldHistoryListen = history.listen;
      const routes = _routes({history});
      history.listen = callback => {
        oldHistoryListen.call(history, location => {
          match({location, routes}, (error, _, state) => {
            if (error) throw new Error(error);
            callback(location, state);
          });
        });
      };
    } catch (e) { /*eslint-disable no-empty*/ }

    // Handle subscriptions.
    _models.forEach(({ subscriptions }) => {
      if (subscriptions) {
        check(subscriptions, is.array, 'Subscriptions must be an array');
        subscriptions.forEach(sub => {
          check(sub, is.func, 'Subscription must be an function');
          sub({dispatch: store.dispatch, history}, onErrorWrapper);
        });
      }
    });

    // Render and hmr.
    if (container) {
      render();
      plugin.apply('onHmr')(render);
    } else {
      const Routes = _routes;
      return () => (
        <Provider store={store}>
          <Routes history={history} />
        </Provider>
      );
    }

    function getWatcher(k, saga) {
      let _saga = saga;
      let _type = 'takeEvery';
      if (Array.isArray(saga)) {
        [ _saga, opts ] = saga;
        opts = opts || {};
        check(opts.type, is.sagaType, 'Type must be takeEvery, takeLatest or watcher');
        warn(opts.type, v => v !== 'takeEvery', 'takeEvery is the default type, no need to set it by opts');
        _type = opts.type;
      }

      function* sagaWithErrorCatch(...arg) {
        try {
          yield _saga(...arg);
        } catch (e) {
          onError(e);
        }
      }

      if (_type === 'watcher') {
        return sagaWithErrorCatch;
      } else if (_type === 'takeEvery') {
        return function*() {
          yield takeEvery(k, sagaWithErrorCatch);
        };
      } else {
        return function*() {
          yield takeLatest(k, sagaWithErrorCatch);
        };
      }
    }

    function* rootSaga() {
      for (let k in sagas) {
        if (sagas.hasOwnProperty(k)) {
          const watcher = getWatcher(k, sagas[k]);
          yield fork(watcher);
        }
      }
    }

    function render(routes) {
      const Routes = routes || _routes;
      ReactDOM.render((
        <Provider store={store}>
          <Routes history={history} />
        </Provider>
      ), container);
    }
  }
Example #28
0
	return function ( next ) {
		return function ( action ) {
			var returnValue;

			console.log( 'will dispatch', action );

			// Call the next dispatch method in the middleware chain.
			returnValue = next( action );

			console.log( 'state after dispatch', getState() );

			// This will likely be the action itself, unless
			// a middleware further in chain changed it.
			return returnValue;
		};
	};
}

if ( process.env.REDUX_LOG === 'on' ) {
	middlewares.push( logger );
}
/* jshint ignore:end */

module.exports = Redux.createStore( Redux.combineReducers( {
	formPagination: formPagination,
	formContent: formContent,
	validity: validity,
	validationMessages: validationMessages
} ), undefined, Redux.applyMiddleware.apply( this, middlewares ) );
Example #29
0
	terms,
	themes,
	ui,
	users,
	wordads
} );

let middleware = [ thunkMiddleware ];

// Analytics middleware currently only works in the browser
if ( typeof window === 'object' ) {
	middleware = [
		...middleware,
		require( './analytics/middleware.js' ).analyticsMiddleware
	];
}

let createStoreWithMiddleware = applyMiddleware.apply( null, middleware );

export function createReduxStore( initialState = {} ) {
	if (
		typeof window === 'object' &&
		window.app &&
		window.app.isDebug &&
		window.devToolsExtension
	) {
		createStoreWithMiddleware = compose( createStoreWithMiddleware, window.devToolsExtension() );
	}
	return createStoreWithMiddleware( createStore )( reducer, initialState );
}
Example #30
0
//external
import { combineReducers, createStore, applyMiddleware } from 'redux';
import createLogger from 'redux-logger';
import thunk from 'redux-thunk';

//internal
import repoReducer from '@src/store/repoReducer';
import uiStateReducer from '@src/store/uiStateReduder';
import AppEnvironment from 'app_environment';

//combine the reducer
const AppReducer = combineReducers({
    repo : repoReducer,//the repo info
    ui : uiStateReducer//the ui state
});

// middlewares to use
const middlewaresToUse = [thunk];

if(AppEnvironment.ENV !== 'prod'){
    // middlewares which are only available in dev mode
    middlewaresToUse.push( createLogger() ); // logging middlewares...
}

const AppStore = createStore( AppReducer, applyMiddleware.apply(null, middlewaresToUse) )

export default AppStore;