Created
April 11, 2017 21:44
-
-
Save kesne/0316e7029a8d22a20a385ded2cf9fdc9 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
import { registerExtension } from './extensionManager'; | |
function createNamespacingMiddleware(reducerKey, reducerNamespace) { | |
return () => next => (action) => { | |
const namespacedAction = action; | |
namespacedAction.meta = { | |
...action.meta, | |
withNamespace: { | |
reducerKey, | |
reducerNamespace, | |
}, | |
}; | |
next(namespacedAction); | |
}; | |
} | |
function createThunkMiddleware(namespacingDispatch) { | |
return ({ namespacedGetState }) => next => (action) => { | |
if (action && typeof action === 'function') { | |
const nextAction = action( | |
namespacingDispatch(), | |
namespacedGetState, | |
); | |
return nextAction; | |
} | |
return next(action); | |
}; | |
} | |
registerExtension('default', ({ reducer, dispatch, lifecycle }) => { | |
// Register listeners: | |
lifecycle.on('mount', () => {}); | |
lifecycle.on('unmount', () => {}); | |
// return an extension: | |
return { | |
augmentGetState: (getState) => { | |
const state = getState(); | |
let reducerState; | |
if (state[reducer.key] === undefined) { | |
reducerState = { [reducer.key]: {} }; | |
} else { | |
reducerState = { | |
[reducer.key]: state[reducer.key][reducer.namespace] || {}, | |
}; | |
} | |
return { | |
...state, | |
...reducerState, | |
}; | |
}, | |
middleware: [ | |
createNamespacingMiddleware(reducer.key, reducer.namespace), | |
createThunkMiddleware(dispatch), | |
], | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment