1 | module.exports = class Hooks {
|
2 | constructor() {
|
3 | this.hooks = new Map()
|
4 | }
|
5 |
|
6 | add(name, fn) {
|
7 | if (!this.hooks.has(name)) {
|
8 | this.hooks.set(name, new Set())
|
9 | }
|
10 | const hook = this.hooks.get(name)
|
11 | hook.add(fn)
|
12 | return this
|
13 | }
|
14 |
|
15 | invoke(name, ...args) {
|
16 | if (this.hooks.has(name)) {
|
17 | this.hooks.get(name).forEach(fn => {
|
18 | fn(...args)
|
19 | })
|
20 | }
|
21 | return this
|
22 | }
|
23 |
|
24 | async invokePromise(name, ...args) {
|
25 | if (this.hooks.has(name)) {
|
26 | for (const fn of this.hooks.get(name)) {
|
27 |
|
28 | await fn(...args)
|
29 | }
|
30 | }
|
31 | return this
|
32 | }
|
33 | }
|