UNPKG

1.06 kBJavaScriptView Raw
1'use strict';
2
3module.exports = class Hooks {
4 constructor() {
5 this._hooks = {};
6 }
7
8 registerHook(name, async = true) {
9 const hooks = this._hooks[name] ? this._hooks[name].hooks || new Set() : new Set();
10 this._hooks[name] = {
11 async,
12 hooks,
13 };
14 return this;
15 }
16
17 addHook(name, handler) {
18 if (!this._hooks[name])
19 this.registerHook(name);
20 if (typeof handler !== 'function')
21 throw new Error('Invalid hook handler');
22 this._hooks[name].hooks.add(handler);
23
24 return () => this._hooks[name].hooks.delete(handler);
25 }
26
27 triggerHook(wire, name, data) {
28 if (!this._hooks[name])
29 throw new Error(`Unknown hook ${name}, have you registered your hook ?`);
30
31 if (this._hooks[name].async)
32 return this.triggerAsyncHook(wire, name, data);
33 return this.triggerSyncHook(wire, name, data);
34 }
35
36 triggerSyncHook(wire, name, data) {
37 for (const handler of this._hooks[name].hooks)
38 handler.call(wire, data);
39 }
40
41 async triggerAsyncHook(wire, name, data) {
42 for (const handler of this._hooks[name].hooks)
43 await handler.call(wire, data);
44 }
45};