2024-10-25 21:19:39 +00:00
|
|
|
import type { WorkerResponse, WorkerRequest } from "./offload.interface";
|
|
|
|
|
|
|
|
declare var self: Worker;
|
|
|
|
|
|
|
|
type HandlerCallback<T, E> = ((data: E) => T) | ((data: E) => Awaited<T>);
|
|
|
|
|
2024-10-25 21:31:12 +00:00
|
|
|
/**
|
|
|
|
* Handler wraps a callback function to be used as a worker handler
|
|
|
|
*/
|
2024-10-25 21:19:39 +00:00
|
|
|
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);
|
|
|
|
});
|
|
|
|
}
|