UNPKG

@toolpad/utils

Version:

Shared utilities used by Toolpad packages.

41 lines 1.32 kB
import { MessagePort } from 'worker_threads'; import { Awaitable } from "./types.js"; /** * Helpers that are intended to set up rpc between a Node.js worker thread and the main thread. * Create the worker and pass a port in the workerData. * * On the main thread: * * const rpcChannel = new MessageChannel() * const worker = new Worker('./myWorker.js', { * workerData: { rpcPort: rpcChannel.port1 }, * transferList: [rpcChannel.port1] * }) * * // Depending of the direction of communication, either * const client = createRpcClient(rpcChannel.port2) * // or * serveRpc(rpcChannel.port2, { * myMethod * }) * * On the worker thread: * * // Depending of the direction of communication, either * const client = createRpcClient(workerData.rpcPort) * // or * serveRpc(workerData.rpcPort, { * myMethod * }) * * Use multiple channels for bidirectional communication. */ export type Methods = Record<string, (...args: any[]) => Awaitable<any>>; interface CreateRpcClientOptions { timeout?: number; } export declare function createRpcClient<M extends Methods>(port: MessagePort, { timeout }?: CreateRpcClientOptions): M; export declare function serveRpc<M extends Methods>(port: MessagePort, methods: M): void; export {};