worker.rpc
This project is a work in progress and is still undergoing much change
A simple library that provides a typesafe rpc interface to web workers.
Install
To add it to your project simply run (not yet published to npm) :
$ npm i git+https://git.suroh.tk/suroh/worker.rpc.git
Usage
You will import the library into both the file that instantiates the worker, as well as the worker itself. Let's create the worker in our client.js
file, set some methods that can be called from the worker itself and call a method from the webWorker itself :
Pre-emptively we are importing the types back from the
worker.ts
file so that our calls to the worker are also typesafe.
// client.js
import { WorkerRpc } from 'worker.rpc'
// types from the worker
import { type WorkerMethods } from './worker.ts'
const webWorker = new Worker('./worker.ts')
const workerRpc = new WorkerRpc<WorkerMethods>(webWorker)
const mainMethods = workerRpc.set({
hello: (name: string) => {
console.log(`Hello ${name}!`)
// calling the method goodBye set in the worker
workerRpc.call.goodBye(name)
}
})
// export the method type
export type MainMethods = typeof mainMethods
Note that we export the type of workerMethods
so that we can safely type the rpc from the worker. The code for this is more or less the same
// worker.js
import { WorkerRpc } from 'worker.rpc'
// types from client.ts
import { type MainMethods } from './client.ts'
const mainRpc = new WorkerRpc<MainMethods>(self)
const workerMethods = mainRpc.set({
goodBye: (name: string) => `Goodbye ${name}!`
})
// calling the method hello set in the client
mainRpc.call.hello('Bob')
// export the method type
export type WorkerMethods = typeof workerMethods
Desires
It would be better if the class could export its own types, or infer the remote types on creation. Right now creating a variable to only export it as typeof
seems clunky. A workaround for this would be setting the methods in the constructor.