offload/offload.handler.ts
2024-10-25 23:31:48 +02:00

18 lines
600 B
TypeScript

import type { WorkerResponse, WorkerRequest } from "./offload.interface";
declare var self: Worker;
type HandlerCallback<T, E> = ((data: E) => T) | ((data: E) => Awaited<T>);
/**
* Handler wraps a callback function to be used as a worker handler
*/
export async function handler<T, E>(fn: HandlerCallback<T, E>): Promise<void> {
self.addEventListener("message", async (event) => {
const request = event.data as WorkerRequest<E>;
const result = await fn(request.params);
const response: WorkerResponse<T> = { id: request.id, value: result };
self.postMessage(response);
});
}