Last active
June 19, 2017 19:11
-
-
Save goatslacker/511a92a4fa154ad4dc9e6b844da6b310 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { | |
applyMiddleware, | |
} = require('redux') | |
function applyGlobalMiddleware(...globalMiddlewares) { | |
return createStore => (reducer, preloadedState, enhancer) => { | |
const scopedMiddleware = [] | |
const injectableMiddleware = store => next => action => { | |
const chain = scopedMiddleware.map(m => m(store)) | |
const dispatch = value => next(value) | |
const injectedMiddleware = chain.reduceRight((n, f) => f(n), dispatch) | |
return injectedMiddleware(action) | |
} | |
function applyScopedMiddleware(actionTypes, middleware) { | |
scopedMiddleware.push(store => next => action => { | |
if (!has(actionTypes, action.type)) return next(action) | |
return middleware(store)(next)(action) | |
}) | |
} | |
const store = createStore( | |
reducer, | |
preloadedState, | |
applyMiddleware(...globalMiddlewares.concat(injectableMiddleware)) | |
) | |
return Object.assign(store, { | |
applyScopedMiddleware, | |
}) | |
} | |
} | |
exports.applyGlobalMiddleware = applyGlobalMiddleware |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment