trpc-webext
v1.0.1
Published
A tRPC adapter & link for WebExtensions
Readme
trpc-webext
A tRPC adapter & link for WebExtensions
Getting Started
Background
import { initTRPC } from '@trpc/server';
import createWebextHandler from 'trpc-webext/adapter';
const t = initTRPC.create({
allowOutsideOfServer: true,
isServer: false,
});
const router = t.router({
// procedures
});
export type Router = typeof router;
createWebextHandler({
router,
});Content Script
import { createTRPCClient } from '@trpc/client';
import webextLink from 'trpc-webext/link';
import type { Router } from './trpc';
const trpc = createTRPCClient<Router>({
links: [webextLink()],
});API Reference
createWebextHandler(options)
| Option | Type | Description | Required |
| --------------- | ---------- | -------------------- | -------- |
| router | Router | tRPC router | Yes |
| createContext | function | tRPC context factory | No |
| onError | function | Error handler | No |
webextLink(options)
| Option | Type | Description | Required |
| ------------- | ------------------------- | ----------------------- | -------- |
| port | Port | Web extension port | No |
| transformer | CombinedDataTransformer | Custom data transformer | No |
Full example
Background
import { initTRPC } from '@trpc/server';
import SuperJSON from 'superjson';
import createWebextHandler from 'trpc-webext/adapter';
interface Context {
someData: string;
}
const t = initTRPC.context<Context>().create({
allowOutsideOfServer: true,
isServer: false,
transformer: SuperJSON,
});
const router = t.router({
// procedures
});
export type Router = typeof router;
createWebextHandler({
router,
createContext: async () => {
return {
someData: 'Hello World!',
};
},
onError: (error) => {
console.error(error);
},
});Content Script
import { createTRPCClient } from '@trpc/client';
import SuperJSON from 'superjson';
import webextLink from 'trpc-webext/link';
import type { Router } from './trpc';
const port = brower.runtime.connect();
const trpc = createTRPCClient<Router>({
links: [
webextLink({
port,
transformer: SuperJSON,
}),
],
});