TypeScript WebWorker RPC
This is a simple RPC utils to build a bridge between window
and worker
as simple way using TypeScript.
Install
yarn add typescript-webworker-rpc
Usage
Quick start
- Define your RPC interface.
- Create an object for server-calling and register handlers.
// Maybe in web-worker context.;new RPCServerself as any .on'add', .on'get',;
- Create an object for client-calling.
// Maybe in window context.; await rpc.call'add', 20;;
Advanced
Let's write an example that communicates each endpoints with ping and pong messages.
- Write two interfaces for that.
// window -> worker// worker -> window
- Write both of client and server using both channels.
// window.ts;new rpc.RPCServerworker.on'pong', ; // worker.ts;new rpc.RPCServerself as any.on'ping', ;
Of course, above example doesn't be terminated because it is the infinity recursive call.
API
RPCClient
A object to call a method to send a request to web-worker side and wait a result using Promise
.
call
await rpc.call`method-name`, ...parameters;
If you send an ArrayBuffer
to web-worker, you can use like this. If you can transfer the ownership of that object, please use withTransfer
method before calling a call
method.
await rpc.withTransfer.call`addBuffer`, buffer;
Of course, you can use multiple parameters, too.
await rpc.call`awesome`, 10, 'good';
post
call
method uses a promise
to wait its result from web-worker. But if you want to post a message and don't need to wait for its result, you can use post
method instead. Its return type should be PostReturn
.
rpc.withTransfer.post`addBuffer`, buffer;
It can reduce meaningless waiting costs when you can fire and forget.
onError
If you want to handle an error from worker
, please chain error
handler using onError
method.
rpc.onErrorconsole.error;
RPCServer
A object to receive a request from window and response a result.
on
(for call
)
You can write a method call handler like event handler.
rpc.on`method-name`, `handler => {result, transfer}`, `transfer`;
If your method is a void function, you can write a void handler. But in other cases, a return type should be {result: ReturnType; transfer?: Transferable[] }
because it should support transfer
like postMessage
.
on
(for post
)
If your handler doesn't need to response due to call from post
function, you should use noReturn
option when installing a method handler.
rpc.on `addBuffer`, , ,;
Then there is no postMessage
for that.
onError
It is same as RPCClient#onError
.
If you want to handle an error from worker
, please chain error
handler using onError
method.
rpc.onErrorconsole.error;
Contributors
Thanks!
License
MIT