GoogleChromeLabs / GoogleChromeLabs/comlink
Making Comlink.proxy() work in node worker threads
- Dominant language
- TypeScript
- Stars
- 12.8k
- Forks
- 435
- PR merge metrics
- No merged PRs in 30d
Description
Took me a while to figure out how to make `Comlink.proxy()` work in node worker threads. I'm not sure that Comlink itself needs to handle this, since the simple workaround is to override the default `proxy` transfer handler. Here's how I did it for anyone curious
```javascript
// In worker-thread
const { parentPort } = require('worker_threads')
const { MessageChannel } = require('worker_threads')
const Comlink = require('comlink')
const nodeEndpoint = require('comlink/dist/umd/node-adapter.js')
// Override comlink's default proxy handler to use Node endpoints
Comlink.transferHandlers.set('proxy', {
canHandle: obj => obj && obj[Comlink.proxyMarker],
serialize: obj => {
const { port1, port2 } = new MessageChannel()
Comlink.expose(obj, nodeEndpoint(port1))
return [port2, [port2]]
},
deserialize: port => {
port = nodeEndpoint(port)
port.start()
return Comlink.wrap(port)
}
})
const thingToProxy = '...'
const api = {
thingToProxy: Comlink.proxy(thingToProxy)
hello () {
return 'HELLO12341567'
},
}
Comlink.expose(api, nodeEndpoint(parentPort))
```
Contributor guide
Assessment
This issue has not been assessed yet.