UNPKG

1.32 kBPlain TextView Raw
1export class Hook {
2 private writeHooks: Map<string, Function> = new Map();
3
4 private readHooks: Map<string, Function> = new Map();
5
6 private generateError(pluginName: string, error: Error) {
7 const generatedError = new Error(`Plugin ${pluginName} failed: ${error.message}`);
8
9 generatedError.stack = error.stack;
10
11 return error;
12 }
13
14 public writeHook(pluginName: string, modifier: Function) {
15 this.writeHooks.set(pluginName, modifier);
16 }
17
18 public readHook(pluginName: string, reader: Function) {
19 this.readHooks.set(pluginName, reader);
20 }
21
22 public async callHooks(...data: Array<any>) {
23 const { writeHooks, readHooks } = this;
24
25 let dataArguments = data;
26
27 for (const [key, hook] of writeHooks) {
28 try {
29 dataArguments = [
30 await hook(...dataArguments),
31 ...dataArguments.slice(1),
32 ];
33 } catch (error) {
34 throw this.generateError(key, error);
35 }
36 }
37
38 for (const [key, hook] of readHooks) {
39 try {
40 await hook(...dataArguments);
41 } catch (error) {
42 throw this.generateError(key, error);
43 }
44 }
45
46 return dataArguments[0];
47 }
48}