-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathhandler.ts
More file actions
28 lines (23 loc) · 799 Bytes
/
handler.ts
File metadata and controls
28 lines (23 loc) · 799 Bytes
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
import { ensureError } from "@mainsail/utils";
import { parentPort } from "worker_threads";
export class Handler<T extends object> {
private readonly handler: T;
public constructor(handler: T) {
this.handler = handler;
parentPort?.on("message", (message) => {
void this.#onMessage(message);
});
}
async #onMessage(message: { method: string; id: string; args: [] }) {
try {
if (this.handler[message.method] === undefined) {
throw new Error(`Method ${message.method} is not defined on the handler`);
}
const result = await this.handler[message.method](...message.args);
parentPort?.postMessage({ id: message.id, result });
} catch (rawError) {
const error = ensureError(rawError);
parentPort?.postMessage({ error: error.message, id: message.id });
}
}
}