-
-
Notifications
You must be signed in to change notification settings - Fork 9.1k
/
decorateAction.ts
35 lines (32 loc) · 1.24 KB
/
decorateAction.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { action } from './action';
import { actions } from './actions';
import { createDecorator } from './withActions';
import { ActionOptions, DecoratorFunction, HandlerFunction } from '../models';
const applyDecorators = (decorators: DecoratorFunction[], actionCallback: HandlerFunction) => {
return (..._args: any[]) => {
const decorated = decorators.reduce((args, storyFn) => storyFn(args), _args);
actionCallback(...decorated);
};
};
export const decorateAction = (decorators: DecoratorFunction[]): ((name: string, options?: ActionOptions) => HandlerFunction) => {
return (name: string, options?: ActionOptions) => {
const callAction = action(name, options);
return applyDecorators(decorators, callAction);
};
};
export const decorate = (decorators: DecoratorFunction[]) => {
const decorated = decorateAction(decorators);
const decoratedActions = (...args: any[]) => {
const rawActions = actions(...args);
const actionsObject = {} as any;
Object.keys(rawActions).forEach(name => {
actionsObject[name] = applyDecorators(decorators, rawActions[name]);
});
return actionsObject;
};
return {
action: decorated,
actions: decoratedActions,
withActions: createDecorator(decoratedActions),
};
};