-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathlifecycle.js
65 lines (58 loc) · 1.35 KB
/
lifecycle.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
59
60
61
62
63
64
65
const eachSeries = require("async.eachseries");
module.exports = class SystemLifecycle {
constructor() {
this.startMethods = [];
this.stopMethods = [];
}
_getMethod(method, context) {
if (typeof method == "string") {
if (!context || !context[method]) {
throw new Error(`Unable to locate start/stop method ${method}`);
}
return context[method];
}
return method;
}
registerStart(priority, method, context) {
this.startMethods.push({
priority,
method: this._getMethod(method, context),
context,
});
}
registerStop(priority, method, context) {
this.stopMethods.push({
priority,
method: this._getMethod(method, context),
context,
});
}
start() {
return new Promise((resolve, reject) => {
eachSeries(
this.startMethods.sort((a, b) => a.priority - b.priority),
({ method, context }, callback) => {
method
.apply(context || null)
.then(() => callback())
.catch(callback);
},
(err) => (err ? reject(err) : resolve())
);
});
}
stop() {
return new Promise((resolve, reject) => {
eachSeries(
this.stopMethods.sort((a, b) => a.priority - b.priority).reverse(),
({ method, context }, callback) => {
method
.apply(context || null)
.then(() => callback())
.catch(callback);
},
(err) => (err ? reject(err) : resolve())
);
});
}
};