forked from cerebral/overmind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathActionChain.ts
More file actions
84 lines (75 loc) · 2.16 KB
/
ActionChain.ts
File metadata and controls
84 lines (75 loc) · 2.16 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import * as EventEmitter from 'eventemitter3'
const IS_DEVELOPMENT = process.env.NODE_ENV !== 'production'
export interface ActionChain<Context> extends EventEmitter {
getOptions(): ActionChainOptions
getContext(
execution: Execution,
path: string[]
): Context & {
execution: Execution
path: string[]
}
}
export type ActionChainOptions = {
actionWrapper?: any
providerExceptions?: string[]
}
export type Execution = {
operatorId: number
actionId: number
executionId: number
}
export function actionChainFactory<Context>(
context: Context,
options: ActionChainOptions = {}
): ActionChain<Context> {
options.providerExceptions = options.providerExceptions || []
return Object.assign(new EventEmitter(), {
getOptions() {
return options
},
getContext(execution: Execution, path: string[]) {
const providers = Object.keys(context).reduce((currentContext, key) => {
if (IS_DEVELOPMENT && options.providerExceptions.indexOf(key) === -1) {
currentContext[key] = Object.keys(context[key]).reduce(
(currentProvider, method) => {
currentProvider[method] = (...args) => {
const result = context[key][method](...args)
if (result instanceof Promise) {
result.then((promisedResult) => {
this.emit('provider', {
...execution,
name: key,
method,
result: promisedResult,
})
})
} else {
this.emit('provider', {
...execution,
name: key,
method,
result,
})
}
return result
}
return currentProvider
},
{}
)
} else {
currentContext[key] = context[key]
}
return currentContext
}, {})
return Object.assign({}, providers, {
execution,
path,
}) as Context & {
execution: Execution
path: string[]
}
},
})
}