-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdialer.ts
85 lines (71 loc) · 2.09 KB
/
dialer.ts
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { existsSync } from "fs";
import { resolve } from "path";
import { Dialer, DialerContext } from "./dialer.types";
// In telephony, a registry is used for maintaining a known set of handlers,
// devices, or processes. This aligns with this class's purpose. Dialers are
// loaded/stored and run in a structured way, so "registry" fits both telephony
// and DI semantics.
export class DialerRegistry {
private readonly dialPath: string;
private preDialers: Dialer[] = [];
private postDialers: Dialer[] = [];
constructor(dialPath: string) {
this.dialPath = dialPath;
}
registerPreDialer(dialer: Dialer) {
this.preDialers.push(dialer);
}
registerPostDialer(dialer: Dialer) {
this.postDialers.push(dialer);
}
async registerDialers() {
const resolvedDialPath = resolve(this.dialPath);
if (!existsSync(resolvedDialPath)) {
console.error(`Error: Dialer file not found: ${resolvedDialPath}`);
process.exit(1);
}
try {
const userModule = await import(resolvedDialPath);
Object.entries(userModule).forEach(([key, fn]) => {
if (typeof fn === "function") {
if (key.startsWith("pre")) {
this.registerPreDialer(fn as Dialer);
} else if (key.startsWith("post")) {
this.registerPostDialer(fn as Dialer);
}
}
});
} catch (error) {
console.error(`Failed to load dialers:`, error);
process.exit(1);
}
}
async executePreDialers(context: DialerContext) {
if (this.preDialers.length === 0) {
return;
}
for (const dial of this.preDialers) {
await dial(context);
}
}
async executePostDialers(context: DialerContext) {
if (this.postDialers.length === 0) {
return;
}
for (const dial of this.postDialers) {
await dial(context);
}
}
}
export class PreDialerError extends Error {
constructor(message: string) {
super(message);
this.name = "Pre-dialer error";
}
}
export class PostDialerError extends Error {
constructor(message: string) {
super(message);
this.name = "Post-dialer error";
}
}