UNPKG

sub-redux

Version:

[![npm version](https://img.shields.io/npm/v/sub-redux.svg)](https://www.npmjs.com/package/sub-redux) [![npm](https://img.shields.io/npm/dm/sub-redux.svg)](https://www.npmjs.com/package/sub-redux)

50 lines (49 loc) 2.24 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var redux_1 = require("redux"); var actions_1 = require("./actions"); var actionHelpers_1 = require("./actionHelpers"); var subStore_1 = require("./subStore"); exports.middleware = function (store) { var chains = {}; return function (next) { return function (action) { if (action.type === 'SUB_REDUX/INIT') { chains[action.payload.instance] = applySubMiddleware(store, action.payload.instance, action.meta.middlewares); } if (action.type === 'SUB_REDUX/DESTROY') { delete chains[action.payload.instance]; } if (actions_1.isSubAction(action)) { // Insert the middleware chain for this sub-instance between this // middleware and next. HOWEVER, the sub-chain needs the unwrapped action, // then we need to rewrap it before passing it on to the next middleware var _a = actionHelpers_1.unwrapSubAction(action), instance_1 = _a.instance, subAction = _a.subAction; var nextWithRewrapped = function (subAction) { return next(actionHelpers_1.wrapSubAction({ instance: instance_1, subAction: subAction })); }; return chains[instance_1](nextWithRewrapped)(subAction); } return next(action); }; }; }; // Inspired by redux's applyMiddleware. function applySubMiddleware(store, instance, middlewares) { var subStore = subStore_1.getSubMiddlewareApi(instance, store); var dispatch = function () { throw new Error('Dispatching while constructing your middleware is not allowed. ' + 'Other middleware would not be applied to this dispatch.'); }; var middlewareAPI = { getState: subStore.getState, dispatch: function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return dispatch.apply(void 0, args); }, }; var chain = middlewares.map(function (m) { return m(middlewareAPI); }); dispatch = function (subAction) { return subStore.dispatch(subAction); }; return redux_1.compose.apply(void 0, chain); }