mirror of
https://github.com/nesterow/offload.git
synced 2024-11-13 21:54:04 +00:00
18 lines
600 B
TypeScript
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);
|
|
});
|
|
}
|