effects with function

main
Yanick Champoux 2023-04-21 15:24:49 -04:00
parent 55f0d5cd13
commit 06b4bf62c4
2 changed files with 37 additions and 4 deletions

View File

@ -314,6 +314,9 @@ export default class Updux<
addEffect(actionCreator:
AggregateActions<ResolveActions<T_LocalActions>, T_Subduxes>,
effect: EffectMiddleware): EffectMiddleware;
addEffect(guardFunc: (action:
AggregateActions<ResolveActions<T_LocalActions>, T_Subduxes>[keyof AggregateActions<ResolveActions<T_LocalActions>, T_Subduxes>]) => boolean,
effect: EffectMiddleware): EffectMiddleware;
addEffect(effect: EffectMiddleware): EffectMiddleware;
addEffect(...args) {
let effect;
@ -323,10 +326,13 @@ export default class Updux<
else {
const [actionCreator, originalEffect] = args;
const test = actionCreator.hasOwnProperty('match') ?
actionCreator.match : actionCreator;
effect = (api) => next => {
const e = originalEffect(api)(next);
return action => {
const func = actionCreator.match(action) ? e : next;
const func = test(action) ? e : next;
return func(action);
}
}

View File

@ -39,7 +39,7 @@ test('buildEffectsMiddleware', () => {
expect(seen).toEqual(0);
const dispatch = vi.fn();
mw({ getState: () => 'the state', dispatch })(() => { })({
mw({ getState: () => 'the state', dispatch })(() => {})({
type: 'noop',
});
expect(seen).toEqual(1);
@ -117,8 +117,35 @@ test('addEffect with actionCreator', () => {
const next = vi.fn();
const spy = vi.fn();
const mw = dux.addEffect(dux.actions.foo, (api) => (next) => (action) =>
next(spy(action))
const mw = dux.addEffect(
dux.actions.foo,
(api) => (next) => (action) => next(spy(action)),
);
mw({})(next)(dux.actions.bar());
expect(next).toHaveBeenCalled();
expect(spy).not.toHaveBeenCalled();
next.mockReset();
mw({})(next)(dux.actions.foo());
expect(next).toHaveBeenCalled();
expect(spy).toHaveBeenCalled();
});
test('addEffect with function', () => {
const dux = new Updux({
actions: {
foo: () => {},
bar: () => {},
},
});
const next = vi.fn();
const spy = vi.fn();
const mw = dux.addEffect(
(action) => action.type[0] === 'f',
(api) => (next) => (action) => next(spy(action)),
);
mw({})(next)(dux.actions.bar());