-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
58 lines (50 loc) · 1.4 KB
/
index.js
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
export default class Interactor {
constructor (context = {}) {
this.context = context
}
static async call (context = {}) {
const instance = new this(context)
return instance.run()
}
async run () {
// group of interactors running
if (this.organize) {
const interactors = []
for (const Interactor of this.organize()) {
const instance = new Interactor(this.context)
const nextContext = await instance.run()
this.context = nextContext
if (this.context.failure) {
for (const instance of interactors) {
await instance.rollback()
}
return this.context
} else {
interactors.push(instance)
}
}
return this.context
}
// single interactor running
try {
if (this.before) await this.before()
await this.call()
if (this.after) await this.after()
this.context = {...this.context, success: true, failure: false}
} catch (error) {
this.context = {...this.context, success: false, failure: true, error}
if (this.rollback) await this.rollback()
if (this.throwOnError) {
throw error
}
}
return this.context
}
call () {
throw new Error('Interactor requires a `call` method to be implemented')
}
fail (msg = 'Failed') {
const err = typeof msg === 'string' ? new Error(msg) : msg
throw err
}
}