augmentMiddlewareApi

main
Yanick Champoux 2023-03-11 17:23:25 -05:00
parent f322691906
commit 5297aecba6
2 changed files with 23 additions and 70 deletions

View File

@ -22,34 +22,35 @@ export const augmentGetState = (originalGetState, selectors) => {
}
return getState;
};
const augmentDispatch = (originalDispatch, actions) => {
const dispatch = (action) => originalDispatch(action);
for (const a in actions) {
dispatch[a] = (...args) => dispatch(actions[a](...args));
}
return dispatch;
};
const augmentMiddlewareApi = (api, actions, selectors) => {
return {
...api,
getState: augmentGetState(api.getState, selectors),
dispatch: augmentDispatch(api.dispatch, actions),
actions,
selectors,
};
};
export function buildEffectsMiddleware(
effects = [],
actions = {},
selectors = {},
) {
return ({
getState: originalGetState,
dispatch: originalDispatch,
...rest
}) => {
const dispatch = (action) => originalDispatch(action);
return (api) => {
const newApi = augmentMiddlewareApi(api, actions, selectors);
for (const a in actions) {
dispatch[a] = (...args) => dispatch(actions[a](...args));
}
const getState = () => originalGetState();
for (const s in selectors) {
getState[s] = (...args) => {
let result = selectors[s](originalGetState());
if (typeof result === 'function') return result(...args);
return result;
};
}
let mws = effects.map((e) =>
e({ getState, dispatch, actions, selectors, ...rest }),
);
let mws = effects.map((e) => e(newApi));
return (originalNext) => {
return mws.reduceRight((next, mw) => mw(next), originalNext);

View File

@ -1,48 +0,0 @@
import { test, expect, vi } from 'vitest';
import { buildMiddleware } from './middleware.js';
import { action } from './actions.js';
test('buildMiddleware, effects', async () => {
const effectMock = vi.fn();
const mw = buildMiddleware([
['*', (api) => (next) => (action) => effectMock()],
]);
mw({})(() => {})({});
expect(effectMock).toHaveBeenCalledOnce();
});
test('buildMiddleware, augmented api', async () => {
const myAction = action('myAction');
const mw = buildMiddleware(
[
[
'*',
(api) => (next) => (action) => {
expect(api.getState.mySelector()).toEqual(13);
api.dispatch(myAction());
next();
},
],
],
{
myAction,
},
{
mySelector: (state) => state?.selected,
},
);
const dispatch = vi.fn();
const getState = vi.fn(() => ({ selected: 13 }));
const next = vi.fn();
mw({ dispatch, getState })(next)(myAction());
expect(next).toHaveBeenCalledOnce();
expect(dispatch).toHaveBeenCalledWith(myAction());
});