Skip to content

Instantly share code, notes, and snippets.

@kesne
Created April 11, 2017 21:44
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 kesne/0316e7029a8d22a20a385ded2cf9fdc9 to your computer and use it in GitHub Desktop.
Save kesne/0316e7029a8d22a20a385ded2cf9fdc9 to your computer and use it in GitHub Desktop.
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