### ORPC Documentation Application Setup Source: https://deepwiki.com/unnoq/orpc/1 This application serves as the central documentation site for the ORPC framework, built with VitePress. It imports all workspace packages for live examples and features Shiki Twoslash for code highlighting and AI-powered search via OpenAI integration. It showcases the framework's capabilities interactively. ```json { "name": "@orpc/docs", "version": "0.1.0", "private": true, "scripts": { "dev": "vitepress dev --host", "build": "vitepress build" }, "dependencies": { "vitepress": "1.0.0-rc.40", "@orpc/client": "workspace:*", "@orpc/contract": "workspace:*", "@orpc/server": "workspace:*", "@orpc/shared": "workspace:*", "@orpc/openapi": "workspace:*", "@orpc/openapi-client": "workspace:*" }, "devDependencies": { "shiki": "1.7.3", "vitepress-plugin-mermaid": "1.0.1", "@vueuse/core": "10.9.0" } } ``` -------------------------------- ### VitePress Documentation Frontmatter Example Source: https://deepwiki.com/unnoq/orpc/9-development-resources An example of the frontmatter structure used in VitePress documentation pages. It includes 'title' and 'description' metadata, essential for SEO and navigation within the documentation site. ```yaml --- title: Event Iterator (SSE) description: Learn how to streaming responses, real-time updates, and server-sent events using oRPC. --- ``` -------------------------------- ### Example ORPC Server Configuration with Plugins Source: https://deepwiki.com/unnoq/orpc/3-server-implementation Demonstrates how to configure an ORPC server with built-in plugins like CORSPlugin and BatchHandlerPlugin. It shows the instantiation of RPCHandler with a router and plugin options. ```typescript import { RPCHandler } from '@orpc/server/fetch' import { CORSPlugin, BatchHandlerPlugin } from '@orpc/server/plugins' const handler = new RPCHandler(router, { plugins: [ new CORSPlugin({ origin: '*', credentials: true, }), new BatchHandlerPlugin({ maxBatchSize: 10, }), ], }) ``` -------------------------------- ### OPTIONS Preflight Handler Example (CORSPlugin) Source: https://deepwiki.com/unnoq/orpc/3 Demonstrates how root interceptors can handle CORS preflight requests by returning a 204 No Content response immediately, bypassing further procedure execution. This example modifies the request context and returns a predefined response. ```typescript // OPTIONS preflight handler - returns immediately without procedure execution options.rootInterceptors.unshift(async (interceptorOptions) => { if (interceptorOptions.request.method === 'OPTIONS') { return { matched: true, response: { status: 204, headers: resHeaders, body: undefined, }, } } return interceptorOptions.next() }) ``` -------------------------------- ### StandardRPCHandler Unit Test with oRPC Source: https://deepwiki.com/unnoq/orpc/9-development-resources This is an example of a unit test for an oRPC handler using the `StandardRPCHandler`. It demonstrates direct procedure invocation with a mock handler and assertion of the response. ```typescript const handler = new StandardRPCHandler({ ping: os.handler(({ input }) => ({ output: input })), }, {}) it('works', async () => { const { response } = await handler.handle({ url: new URL('https://example.com/api/v1/ping'), body: () => Promise.resolve({ json: 'value' }), // ... }) expect(response?.body).toEqual({ json: { output: 'value' } }) }) ``` -------------------------------- ### TypeScript Handler Integration Testing Source: https://deepwiki.com/unnoq/orpc/3-server-implementation Shows how to perform integration testing for handlers by simulating HTTP requests. This example uses `StandardRPCHandler` and mocks a request to test the handler's response. ```typescript import { StandardRPCHandler } from '@orpc/server' const handler = new StandardRPCHandler({ ping: os.handler(() => 'pong') }, {}) const { response } = await handler.handle({ url: new URL('https://example.com/api/v1/ping'), body: () => Promise.resolve({ json: 'value' }), headers: {}, method: 'POST', signal: undefined, }, { prefix: '/api/v1', context: {}, }) expect(response?.body).toEqual({ json: { output: 'pong' } }) ``` -------------------------------- ### SSR/SSG Pattern: Efficient Data Fetching for Server-Side Rendering Source: https://deepwiki.com/unnoq/orpc/8 This code demonstrates how Server-Side Rendering (SSR) and Static Site Generation (SSG) can efficiently fetch data using ORPC. The `createRouterClient` function is used to get a client with a database context, and then `client.content.list` is called within `getServerSideProps` in a Next.js page to fetch data, optimizing data retrieval for rendering. ```typescript import { createRouterClient } from '@orpc/server' const client = createRouterClient(router, { context: { db: getDatabaseConnection() } }) // In Next.js page/component export async function getServerSideProps() { const data = await client.content.list({ limit: 10 }) return { props: { data } } } ``` -------------------------------- ### Background Jobs Pattern: Invoking Procedures from Queue Processors Source: https://deepwiki.com/unnoq/orpc/8 This example demonstrates how queue processors can invoke ORPC procedures directly using a router client. The `createRouterClient` function sets up a client with a database connection context, and then the `client.email.send` procedure is called to process a background job, highlighting efficient background task execution. ```typescript import { createRouterClient } from '@orpc/server' const client = createRouterClient(router, { context: { db: getDatabaseConnection() } }) // In queue processor async function processJob(job: Job) { await client.email.send({ to: job.data.email, subject: job.data.subject, body: job.data.body, }) } ``` -------------------------------- ### oRPC Validation Index Calculation (TypeScript) Source: https://deepwiki.com/unnoq/orpc/5-schema-validation Provides code examples illustrating how oRPC calculates the final validation indices for input and output based on initial configurations and the number of registered middlewares. ```typescript // From packages/server/src/builder.ts:249 inputValidationIndex: fallbackConfig('initialInputValidationIndex', this['~orpc'].config.initialInputValidationIndex) + this['~orpc'].middlewares.length; // From packages/server/src/builder.ts:264 outputValidationIndex: fallbackConfig('initialOutputValidationIndex', this['~orpc'].config.initialOutputValidationIndex) + this['~orpc'].middlewares.length; ``` -------------------------------- ### Implementing Plugin Order and Composition with RPCLink Source: https://deepwiki.com/unnoq/orpc/4 Plugins are executed in ascending order based on the 'order' property, allowing control over sequence like placing custom logic before retry and batching. The example shows a CustomPlugin with interceptors added to options, integrated into RPCLink with other plugins. Dependencies include StandardLinkPlugin interface and required plugins; inputs are link URL and plugin array, outputs configured RPCLink instance. Limitation: Order must be carefully managed to avoid incorrect wrapping, e.g., batching after retry. ```typescript class CustomPlugin implements StandardLinkPlugin { order = 1_000_000 // Execute before retry (1,800,000) init(options: StandardLinkOptions): void { options.interceptors = options.interceptors ?? [] options.interceptors.push(async (opts) => { // Custom logic return opts.next() }) } } const link = new RPCLink({ url: 'http://localhost:3000/rpc', plugins: [ new CustomPlugin(), // order: 1,000,000 new ClientRetryPlugin(), // order: 1,800,000 new BatchLinkPlugin({ // order: 5,000,000 groups: [{ condition: () => true, context: {} }] }) ] }) ``` -------------------------------- ### Configure OpenAPILink with Retry Client Plugin Source: https://deepwiki.com/unnoq/orpc/4 Illustrates how to configure an OpenAPILink instance with the ClientRetryPlugin. This example shows adding retry functionality to OpenAPI requests, with a default setting to retry failed requests up to 3 times. This is essential for handling transient network issues in API communication. ```typescript import { OpenAPILink } from '@deepwiki/client'; import { ClientRetryPlugin } from '@deepwiki/client/plugins/retry'; // Assume 'contract' is defined elsewhere // const contract = ...; // OpenAPILink with plugins const link = new OpenAPILink(contract, { url: 'http://localhost:3000/api', plugins: [ new ClientRetryPlugin({ default: { retry: 3 } }), ], }); ``` -------------------------------- ### TypeScript Twoslash for Type-Checked Examples Source: https://deepwiki.com/unnoq/orpc/9-development-resources Demonstrates how TypeScript Twoslash is used to provide type-checked code examples with inline type information. This method ensures code snippets remain accurate and up-to-date with API changes. It is primarily used for showcasing API call patterns and type inference. ```typescript // Example with type inference shown const result = await orpc.planet.find({ id: 1 }) // ^? inferred type displayed ``` -------------------------------- ### Recommended Import Patterns (JavaScript/TypeScript) Source: https://deepwiki.com/unnoq/orpc/10-reference Demonstrates recommended and direct import patterns for oRPC packages. The recommended pattern minimizes dependencies, while the direct pattern is useful for shared utilities. ```javascript // Recommended Import Pattern // Import from the primary package you're using import { os, EventPublisher, eventIteratorToStream, onError } from '@orpc/server'; // Or from client package import { createORPCClient, EventPublisher, streamToEventIterator } from '@orpc/client'; ``` ```javascript // Direct Import Pattern (Advanced) // Import directly from @orpc/shared (less common) import { EventPublisher, asyncIteratorToStream } from '@orpc/shared'; ``` -------------------------------- ### StandardHandler Constructor for Plugin Initialization Source: https://deepwiki.com/unnoq/orpc/3 Illustrates the constructor logic for the StandardHandler, showing how it initializes a CompositeStandardHandlerPlugin and registers root, request, and client interceptors. It takes options including plugins, router, matcher, and codec. ```typescript constructor( router: Router, private readonly matcher: StandardMatcher, private readonly codec: StandardCodec, options: NoInfer>, ) { const plugins = new CompositeStandardHandlerPlugin(options.plugins) plugins.init(options, router) this.interceptors = toArray(options.interceptors) this.clientInterceptors = toArray(options.clientInterceptors) this.rootInterceptors = toArray(options.rootInterceptors) this.matcher.init(router) } ``` -------------------------------- ### oRPC Error Handling with Type-Safe Constructors Source: https://deepwiki.com/unnoq/orpc/2-core-concepts Example demonstrating how to define and use type-safe error constructors in oRPC. This ensures that error data conforms to predefined schemas. ```typescript import { z } from "zod"; import { createBuilder } from "@orpc/server"; const builder = createBuilder({ // ... other config }); const errors = builder.errors({ UNAUTHORIZED: { status: 401, message: 'Unauthorized' }, NOT_FOUND: { status: 404, data: z.object({ id: z.string() }) } }); // Example usage within a handler: // throw errors.UNAUTHORIZED(); // Type-safe, no data required // throw errors.NOT_FOUND({ id: '123' }); // Type-safe, data required ``` -------------------------------- ### Configure LLMS Plugin for Documentation Generation Source: https://deepwiki.com/unnoq/orpc/9 Configures the vitepress-plugin-llms to generate LLM-friendly documentation formats and adds copy/download buttons to markdown. The plugin ignores blog and learning content to focus on API documentation. ```typescript llmstxt({ ignoreFiles: [ 'blog/*', 'learn-and-contribute/*', ], }) ``` -------------------------------- ### Initialize OpenTelemetry SDK Source: https://deepwiki.com/unnoq/orpc/8-advanced-features Shows how to configure the OpenTelemetry SDK at application startup, including setting up a Jaeger exporter for trace collection. ```TypeScript // app.ts (application initialization) import { NodeSDK } from '@opentelemetry/sdk-node' import { JaegerExporter } from '@opentelemetry/exporter-jaeger' const sdk = new NodeSDK({ serviceName: 'orpc-api', traceExporter: new JaegerExporter({ endpoint: 'http://localhost:14268/api/traces' }) }) sdk.start() // Now oRPC procedures with runWithSpan will automatically trace ``` -------------------------------- ### Initialize Root Builder in TypeScript Source: https://deepwiki.com/unnoq/orpc/10 This code initializes the root 'os' builder with default configurations and middlewares, serving as the base for derived builders. It depends on Builder class, DEFAULT_CONFIG, and fallbackConfig function. creates a Builder instance with default settings, used for inheritance in router architectures with no specific limitations. ```typescript export const os = new Builder({ config: {}, // ... other properties inputValidationIndex: fallbackConfig('initialInputValidationIndex'), outputValidationIndex: fallbackConfig('initialOutputValidationIndex'), middlewares: [], dedupeLeadingMiddlewares: true, }) ``` -------------------------------- ### MessagePort Adapter for Worker Threads Source: https://deepwiki.com/unnoq/orpc/3-server-implementation Demonstrates the MessagePort adapter usage in Node.js Worker Threads. The adapter listens for messages containing a MessagePort, upgrades it for RPC communication, and starts the port for message handling. ```JavaScript // worker.js import { parentPort } from 'node:worker_threads' import { RPCHandler } from '@orpc/server/message-port' const handler = new RPCHandler(router) parentPort.on('message', (message) => { if (message instanceof MessagePort) { handler.upgrade(message, { context: {} }) message.start() } }) ``` -------------------------------- ### Configure Sitemap for Search Engine Indexing Source: https://deepwiki.com/unnoq/orpc/9 Configures the sitemap plugin with hostname and last modified date settings to enable search engine indexing of the documentation site. ```typescript sitemap: { hostname: 'https://orpc.unnoq.com', lastmodDateOnly: true, } ``` -------------------------------- ### Define Valibot schema for procedure input Source: https://deepwiki.com/unnoq/orpc/5-schema-validation Example showing how to use Valibot schemas as input for oRPC procedures. The input is automatically typed based on the Valibot schema definition. Requires valibot package. ```typescript import * as v from 'valibot' const schema = v.object({ name: v.string(), age: v.number(), }) const procedure = os .input(schema) .handler(async ({ input }) => { // input is typed from Valibot schema }) ``` -------------------------------- ### Solid Query Integration: Create Query Source: https://deepwiki.com/unnoq/orpc/7 Demonstrates basic usage of oRPC with Solid Query for reactive data fetching in SolidJS components. It requires `@orpc/client` and `@orpc/solid-query`. The `createQuery` function provides reactive query results that can be directly used within Solid's reactive system. ```javascript // Client setup import { createORPCClient } from '@orpc/client' import { solidQueryUtils } from '@orpc/solid-query' const client = createORPCClient({ /* ... */ }) const utils = solidQueryUtils(client) // In component function UserProfile() { const query = utils.user.get.createQuery({ input: { id: '123' } }) return ( Loading...}>
{query.data.name}
) } ``` -------------------------------- ### Configure OpenAPI generator with schema converters Source: https://deepwiki.com/unnoq/orpc/5-schema-validation Example showing how to register schema converters with the OpenAPIGenerator to convert validation schemas to JSON Schema for OpenAPI spec generation. Supports multiple converters with automatic selection. ```typescript import { OpenAPIGenerator } from '@orpc/openapi' import { ZodToJsonSchemaConverter } from '@orpc/zod/zod4' const generator = new OpenAPIGenerator({ schemaConverters: [new ZodToJsonSchemaConverter()] }) const spec = await generator.generate(router, { info: { title: 'Planet API', version: '1.0.0' } }) ``` -------------------------------- ### Configure Local Search with Custom Ranking Source: https://deepwiki.com/unnoq/orpc/9 Sets up VitePress's local search provider with detailed view enabled and custom ranking logic that de-emphasizes learning content in search results by applying a 0.5 boost factor. ```typescript search: { provider: 'local', options: { detailedView: true, miniSearch: { searchOptions: { boostDocument(docId: string) { if (docId.startsWith('/learn-and-contribute/')) { return 0.5 // Lower ranking for learning content } return 1 }, }, }, }, } ``` -------------------------------- ### Customize validation error handling with error maps Source: https://deepwiki.com/unnoq/orpc/5-schema-validation Example showing how to customize validation error responses using error maps defined with the .errors() method. Provides type-safe error constructors and structured error data. ```typescript const procedure = os .errors({ VALIDATION_ERROR: { message: 'Invalid input data', status: 400 } }) .input(schema) .handler(async ({ errors }) => { // errors.VALIDATION_ERROR is available as a constructor throw new errors.VALIDATION_ERROR({ details: 'Custom validation message' }) }) ``` -------------------------------- ### Configure Open Graph Meta Tags for Social Sharing Source: https://deepwiki.com/unnoq/orpc/9 Sets up Open Graph meta tags for proper social media sharing, including image and type configuration for the documentation website. ```html ['meta', { property: 'og:image', content: 'https://orpc.unnoq.com/og.jpg' }], ['meta', { property: 'og:type', content: 'website' }], ``` -------------------------------- ### Define Zod schema with extended types Source: https://deepwiki.com/unnoq/orpc/5-schema-validation Example showing how to use @orpc/zod extended schema types for file, URL and RegExp validation. Includes OpenAPI metadata enhancement using oz.openapi(). Requires @orpc/zod and zod packages. ```typescript import { oz } from '@orpc/zod' import * as z from 'zod' const schema = z.object({ avatar: oz.file().type('image/png'), website: oz.url(), pattern: oz.regexp(), }) // OpenAPI extensions const enhanced = oz.openapi(schema, { examples: [{ avatar: new File([], 'avatar.png'), website: new URL('https://example.com') }] }) ``` -------------------------------- ### Fetch API Adapter Usage Source: https://deepwiki.com/unnoq/orpc/3-server-implementation Demonstrates how to use the Fetch API adapter with RPCHandler. This adapter is suitable for environments supporting the Fetch API like Cloudflare Workers, Deno Deploy, Bun, and Node.js 18+. It includes handling unmatched requests with a 404 response. ```TypeScript import { RPCHandler } from '@orpc/server/fetch' const handler = new RPCHandler(router, { plugins: [new CORSPlugin()], }) export default async function fetch(request: Request) { const { matched, response } = await handler.handle(request, { prefix: '/rpc', context: {}, }) if (matched) { return response } return new Response('Not Found', { status: 404 }) } ``` -------------------------------- ### Configure Cache-Aware Batching with RPCLink (TypeScript) Source: https://deepwiki.com/unnoq/orpc/4 Sets up a BatchLinkPlugin that groups requests based on cache strategy, choosing GET for cached calls and POST otherwise. Requires a ClientContext with an optional cache field. Returns batched responses per group. ```TypeScript interface ClientContext { cache?: RequestCache } const link = new RPCLink({ url: 'http://localhost:3000/rpc', method: ({ context }) => context?.cache ? 'GET' : 'POST', plugins: [ new BatchLinkPlugin({ groups: [ { condition: ({ context }) => context?.cache === 'force-cache', context: { cache: 'force-cache' } }, { condition: () => true, context: {} } ] }) ], fetch: (request, init, { context }) => globalThis.fetch(request, { ...init, cache: context?.cache }) }) ``` -------------------------------- ### Integrate ORPC with Hono using Fetch Handler Source: https://deepwiki.com/unnoq/orpc/3-server-implementation Sets up an ORPC fetch handler within a Hono app to serve RPC under a /rpc/* prefix. The handler matches routes and returns responses; unmatched requests are returned as 404. Requires a predefined router and the @orpc/server/fetch package. Limited to HTTP/1.1/HTTP/2 fetch semantics; ensure the router is defined before use. ```javascript import { Hono } from 'hono' import { RPCHandler } from '@orpc/server/fetch' const app = new Hono() const handler = new RPCHandler(router, {}) app.all('/rpc/*', async (c) => { const { matched, response } = await handler.handle(c.req.raw, { prefix: '/rpc', context: {}, }) if (matched) { return response } return c.text('Not Found', 404) }) ``` -------------------------------- ### TypeScript Client Context for oRPC Source: https://deepwiki.com/unnoq/orpc/8-advanced-features Demonstrates the ClientContext type parameter in oRPC, enabling per-call context customization. It shows how to define a context interface and use it in a client creation function, including an example of overriding context for a specific call. ```typescript interface ClientContext { cache?: boolean // Optional: defaults not required } const client = createRouterClient({ ping, pong }, { context: ({ cache }: ClientContext) => { if (cache) { return { cacheEnabled: true } // Context when cache enabled } return { cacheEnabled: false } // Context when cache disabled } }) // Per-call context override const result = await client.ping(undefined, { context: { cache: true } }) ``` -------------------------------- ### Integration with Server and Client Source: https://deepwiki.com/unnoq/orpc/6-openapi-integration Describes how to integrate OpenAPI generation and handling on both the server and client sides. ```APIDOC ## Integration with Server and Client ### Server-Side Integration Both `OpenAPIHandler` and `OpenAPIGenerator` can accept routers or contracts. The generator uses `resolveContractProcedures()` to traverse all procedures. ### Client-Side Integration The `OpenAPILink` consumes OpenAPI endpoints with full type safety, inferring HTTP methods from route metadata and handling JSON serialization. ``` -------------------------------- ### Configuration-Driven Validation Index Calculation Source: https://deepwiki.com/unnoq/orpc/10 Implements fallback logic for calculating initial validation indexes using configuration values. The code demonstrates how validation positions are determined based on the builder's configuration, with fallback to default values when needed. Used when context is reset to preserve configuration integrity. ```typescript inputValidationIndex: fallbackConfig('initialInputValidationIndex', this['~orpc'].config.initialInputValidationIndex) outputValidationIndex: fallbackConfig('initialOutputValidationIndex', this['~orpc'].config.initialOutputValidationIndex) ``` -------------------------------- ### fallbackConfig Function in TypeScript Source: https://deepwiki.com/unnoq/orpc/10 This function resolves configuration values by falling back to defaults if undefined, ensuring consistent config handling. It takes a config key and optional value, with no external dependencies. Outputs the resolved config value, suitable for validation and middleware setups without limitations. ```typescript function fallbackConfig( key: T, value?: Config[T] ): Config[T] { if (value === undefined) { return DEFAULT_CONFIG[key] } return value } ``` -------------------------------- ### Testing Pattern: Simplifying Unit and Integration Tests Source: https://deepwiki.com/unnoq/orpc/8 This snippet illustrates how to simplify unit and integration testing by directly invoking procedures using the `call` function from `@orpc/server`. It shows a test case for finding a user by ID, providing a mock database context, which is crucial for isolated and repeatable testing of server-side logic. ```typescript import { call } from '@orpc/server' describe('user procedures', () => { it('should find user by id', async () => { const result = await call(findUser, { id: '123' }, { context: { db: mockDatabase } }) expect(result).toEqual({ id: '123', name: 'Test User' }) }) }) ``` -------------------------------- ### NestJS Framework Integration for ORPC Source: https://deepwiki.com/unnoq/orpc/1 This package integrates ORPC with the NestJS framework, offering decorators and module setup for seamless integration. It depends on several other ORPC workspace packages, including client, contract, openapi, server, and shared modules. This facilitates building ORPC services within a NestJS application. ```yaml dependencies: "@orpc/client": "workspace:" "@orpc/contract": "workspace:" "@orpc/openapi": "workspace:" "@orpc/openapi-client": "workspace:" "@orpc/server": "workspace:" "@orpc/shared": "workspace:" "@orpc/standard-server": "workspace:" "@orpc/standard-server-node": "workspace:" ``` -------------------------------- ### Basic Usage of oRPC SWR Hooks in React Source: https://deepwiki.com/unnoq/orpc/7 This snippet demonstrates setting up an oRPC client with SWR utilities and using hooks for queries and mutations in React components. It requires @orpc/client, @orpc/experimental-react-swr, SWR >=2.3.6, and React >=18.0.0. Inputs include procedure paths and parameters like user ID; outputs provide data, error, loading states for queries, and trigger functions for mutations. Limitations include no built-in infinite queries or devtools support. ```typescript // Client setup import { createORPCClient } from '@orpc/client' import { swrUtils } from '@orpc/experimental-react-swr' const client = createORPCClient({ /* ... */ }) const utils = swrUtils(client) // In component function UserProfile() { const { data, error, isLoading } = utils.user.get.useSWR({ input: { id: '123' } }) if (isLoading) return
Loading...
if (error) return
Error: {error.message}
return
{data.name}
} // Mutations function UpdateUser() { const { trigger, isMutating } = utils.user.update.useSWRMutation() const handleUpdate = async () => { await trigger({ id: '123', name: 'New Name' }) } return } ``` -------------------------------- ### Apply ESLint Rules to Content Files Source: https://deepwiki.com/unnoq/orpc/9 Configures ESLint to apply relaxed linting rules specifically to documentation content directories. Allows console usage, unrestricted imports, and flexible import ordering within specified paths. ```javascript files: [ 'apps/content/shared/**', 'apps/content/blog/**', 'apps/content/docs/**', 'apps/content/examples/**', 'apps/content/learn-and-contribute/**', 'playgrounds/**', 'packages/*/playground/**', ] ``` -------------------------------- ### Configuring BatchLinkPlugin for Streaming Mode Source: https://deepwiki.com/unnoq/orpc/4 The streaming mode is the default for BatchLinkPlugin, allowing asynchronous responses to be yielded as they complete without waiting for all requests. It uses an async iterator for the batch response and is suitable for environments supporting streaming. No specific dependencies beyond the plugin itself; input is plugin options including groups, output is an async iterable of responses. Limitation: Not compatible with non-streaming environments like some serverless setups. ```typescript new BatchLinkPlugin({ groups: [{ condition: () => true, context: {} }], mode: 'streaming' // Default }) ``` -------------------------------- ### Generator Configuration Source: https://deepwiki.com/unnoq/orpc/6-openapi-integration Details the configuration options for the OpenAPI generator, including constructor options and generate options. ```APIDOC ## Generator Configuration ### Constructor Options The `OpenAPIGeneratorOptions` interface allows for custom schema converters. ```typescript interface OpenAPIGeneratorOptions { schemaConverters?: ConditionalSchemaConverter[]; // ...extends StandardOpenAPIJsonSerializerOptions } ``` The `schemaConverters` array is used by `CompositeSchemaConverter` to match converters. ### Generate Options The `OpenAPIGeneratorGenerateOptions` interface accepts several options for generating the OpenAPI specification: | Option | Type | Purpose | |---------------|-----------------------------|-----------------------------------------------| | `info` | `OpenAPI.InfoObject` | API title, version, description | | `filter` | `(options) => boolean` | Exclude procedures from the spec | | `commonSchemas`| `Record` | Reusable component schemas | | `servers`, `tags`, etc | Various | Standard OpenAPI document fields | The `filter` option (replacing `exclude`) uses `TraverseContractProcedureCallbackOptions` to selectively generate the spec. ``` -------------------------------- ### Fastify Integration with RPCHandler Source: https://deepwiki.com/unnoq/orpc/3-server-implementation Shows how to integrate the ORPC server with a Fastify application. It sets up a catch-all route to handle RPC requests using `RPCHandler` and integrates with Fastify's request and reply objects. ```typescript import Fastify from 'fastify' import { RPCHandler } from '@orpc/server/fetch' const fastify = Fastify() const handler = new RPCHandler(router, {}) fastify.all('/rpc/*', async (request, reply) => { const { matched, response } = await handler.handle(request.raw, { prefix: '/rpc', context: {}, }) if (matched) { return reply.send(response) } return reply.status(404).send('Not Found') }) ``` -------------------------------- ### Integrate PostHog Analytics for Usage Tracking Source: https://deepwiki.com/unnoq/orpc/9 Configures PostHog analytics integration for tracking page views, user flows, and feature usage to inform documentation improvements and user experience analysis. ```typescript ['script', {}, ` !function(t,e){...}(document,window.posthog||[]); posthog.init('phc_YHeqjC9tR604AHH45kQi63fT4aBvpsS7zAaCxntBzZm', { api_host: 'https://us.i.posthog.com', person_profiles: 'always', }) `] ```