-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathbridge.ts
48 lines (42 loc) · 1.22 KB
/
bridge.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
36
37
38
39
40
41
42
43
44
45
46
47
48
import type { Action, Store } from './store';
type ActionCreator<P, S> = (payload: P) => Action<S>;
interface BridgeStore<T extends object> {
store: Store<T>;
actions: { [key: string]: ActionCreator<unknown, T> };
}
interface StoreAction<P, S extends object> {
key: string;
store: Store<S>;
actionCreator: ActionCreator<P, S>;
}
const actionMap: { [key: string]: StoreAction<unknown, object>[] } = {};
export const registerBridgeStore = <T extends object>(
...stores: BridgeStore<T>[]
): void => {
for (const store of stores) {
for (const [key, actionCreator] of Object.entries(store.actions)) {
if (actionMap[key] === undefined) {
actionMap[key] = [];
}
actionMap[key].push({
key,
store: store.store as unknown as Store<object>,
actionCreator: actionCreator as unknown as ActionCreator<
unknown,
object
>,
});
}
}
};
export const onStoreAction = async <T>(
event: string,
payload: T
): Promise<void> => {
if (actionMap[event] !== undefined && actionMap[event].length > 0) {
const actions = actionMap[event];
for (const action of actions) {
await action.store.dispatch(action.actionCreator(payload));
}
}
};