-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathModifiersWorker.ts
51 lines (45 loc) · 2.06 KB
/
ModifiersWorker.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
49
50
51
import { getAllMethodsFromModule } from './helpers/module'
import { StonexModule } from './StonexModule'
import { Store } from './StonexStore'
export declare type StoreModifier<MP, D = ModuleModifier> = (store: Store<MP> | null) => (void | D)
export declare type ModuleModifier<D = ActionModifier> = (module: StonexModule) => (void | D)
export declare type ActionModifier = (args: any[], moduleName: string, methodName: string) => false | any
export declare type Modifier<MP> = StoreModifier<MP>
/**
* Internal class which usings only in StonexStore code
* Allows to convert outer modifiers to Action/Module/Store specific modifiers
*
*/
export class ModifiersWorker {
public static getModuleModifiers<MP> (modifiers: Array<Modifier<MP>>, storeInstance: Store<MP>): ModuleModifier[] {
return modifiers.reduce((moduleModifiers: ModuleModifier[], modifier) => {
const moduleModifier: ModuleModifier | any = modifier(storeInstance)
if (typeof moduleModifier === 'function') {
moduleModifiers.push(moduleModifier)
}
return moduleModifiers
},[])
}
public static getActionModifiers (moduleModifiers: ModuleModifier[], moduleInstance: StonexModule): ActionModifier[] {
return moduleModifiers.reduce((actionModifiers: ActionModifier[], moduleModifier: ModuleModifier) => {
const actionModifier: ActionModifier | any = moduleModifier(moduleInstance)
if (typeof actionModifier === 'function') {
actionModifiers.push(actionModifier)
}
return actionModifiers
}, [])
}
public static attachActionModifiersToModule (actionModifiers: ActionModifier[], moduleInstance: StonexModule): void {
getAllMethodsFromModule(moduleInstance).forEach(methodName => {
const closuredMethod = moduleInstance[methodName]
moduleInstance[methodName] = (...args: any[]) => {
for (const modifier of actionModifiers) {
if (modifier(args, moduleInstance.moduleName, methodName) === false) {
return null
}
}
return closuredMethod.apply(moduleInstance, args)
}
})
}
}