-
Notifications
You must be signed in to change notification settings - Fork 28
/
hookable.js
65 lines (55 loc) · 1.33 KB
/
hookable.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 { serial, flatHooks } = require('./utils')
module.exports = class Hookable {
constructor (logger = console) {
this._logger = logger
this._hooks = {}
this._deprecatedHooks = {}
this.hook = this.hook.bind(this)
this.callHook = this.callHook.bind(this)
}
hook (name, fn) {
if (!name || typeof fn !== 'function') {
return
}
if (this._deprecatedHooks[name]) {
this._logger.warn(`${name} hook has been deprecated, please use ${this._deprecatedHooks[name]}`)
name = this._deprecatedHooks[name]
}
this._hooks[name] = this._hooks[name] || []
this._hooks[name].push(fn)
}
deprecateHook (old, name) {
this._deprecatedHooks[old] = name
}
addHooks (configHooks) {
const hooks = flatHooks(configHooks)
for (const key in hooks) {
this.hook(key, hooks[key])
}
}
async callHook (name, ...args) {
if (!this._hooks[name]) {
return
}
try {
await serial(this._hooks[name], fn => fn(...args))
} catch (err) {
if (name !== 'error') {
await this.callHook('error', err)
}
if (this._logger.fatal) {
this._logger.fatal(err)
} else {
this._logger.error(err)
}
}
}
clearHook (name) {
if (name) {
delete this._hooks[name]
}
}
clearHooks () {
this._hooks = {}
}
}