32 lines
1.3 KiB
JavaScript
32 lines
1.3 KiB
JavaScript
import { augmentGetState } from './createStore.js';
|
|
export function buildEffects(localEffects, subduxes = {}) {
|
|
return [
|
|
...localEffects,
|
|
...Object.entries(subduxes).flatMap(([slice, { effects, actions, selectors }]) => {
|
|
if (!effects)
|
|
return [];
|
|
return effects.map((effect) => (api) => effect(augmentMiddlewareApi(Object.assign(Object.assign({}, api), { getState: () => api.getState()[slice] }), actions, selectors)));
|
|
}),
|
|
];
|
|
}
|
|
export function buildEffectsMiddleware(effects = [], actions = {}, selectors = {}) {
|
|
return (api) => {
|
|
const newApi = augmentMiddlewareApi(api, actions, selectors);
|
|
let mws = effects.map((e) => e(newApi));
|
|
return (originalNext) => {
|
|
return mws.reduceRight((next, mw) => mw(next), originalNext);
|
|
};
|
|
};
|
|
}
|
|
export const augmentMiddlewareApi = (api, actions, selectors) => {
|
|
return Object.assign(Object.assign({}, api), { getState: augmentGetState(api.getState, selectors), dispatch: augmentDispatch(api.dispatch, actions), actions,
|
|
selectors });
|
|
};
|
|
const augmentDispatch = (originalDispatch, actions) => {
|
|
const dispatch = (action) => originalDispatch(action);
|
|
for (const a in actions) {
|
|
dispatch[a] = (...args) => dispatch(actions[a](...args));
|
|
}
|
|
return dispatch;
|
|
};
|