Utility Process API
import { createParentPortHandler } from 'electron-messageport-trpc/utility';createParentPortHandler(opts)
Section titled “createParentPortHandler(opts)”Attaches a tRPC request handler to the utility process’s parentPort. This allows the main process (or, via brokering, a renderer) to call tRPC procedures running in a utility process.
Parameters
Section titled “Parameters”interface CreateParentPortHandlerOptions<TRouter extends AnyRouter> { router: TRouter; parentPort: ParentPort; createContext?: () => Promise<unknown>;}| Parameter | Type | Required | Description |
|---|---|---|---|
router | AnyRouter | Yes | Your tRPC router instance |
parentPort | ParentPort | Yes | The utility process parent port from electron |
createContext | () => Promise<unknown> | No | Factory function called for every request |
Returns
Section titled “Returns”A { handlers: PortHandler[] } object. Each transferred port creates one handler.
Example
Section titled “Example”import { createParentPortHandler } from 'electron-messageport-trpc/utility';import { initTRPC } from '@trpc/server';
const t = initTRPC.create();
const router = t.router({ heavyComputation: t.procedure.query(async () => { // Runs in a separate thread, not blocking the main process return performExpensiveWork(); }),});
createParentPortHandler({ router, parentPort: process.parentPort,});// main processimport { MessageChannelMain, utilityProcess } from 'electron';import { createTRPCClient } from '@trpc/client';import { mainPortLink } from 'electron-messageport-trpc/main';
const child = utilityProcess.fork('utility-worker.js');const { port1, port2 } = new MessageChannelMain();
child.postMessage({ type: 'connect' }, [port1]);
const client = createTRPCClient({ links: [mainPortLink({ port: port2 })],});Use Cases
Section titled “Use Cases”- CPU-intensive computation without blocking the main process
- File processing in a background thread
- Database operations isolated from the main process
- Renderer-to-utility brokering when the main process should only hand off a port