Skip to content

Instantly share code, notes, and snippets.

@goatslacker
Last active June 19, 2017 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goatslacker/511a92a4fa154ad4dc9e6b844da6b310 to your computer and use it in GitHub Desktop.
Save goatslacker/511a92a4fa154ad4dc9e6b844da6b310 to your computer and use it in GitHub Desktop.
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