本地链接
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
localLink 是一个终止链接,它允许你在应用程序中直接进行 tRPC 过程调用,而无需经过 HTTP 协议。
信息
由于这是新 API,我们为其添加了 unstable_ 前缀,但你可以安全使用!了解更多。
用法
tsximport {createTRPCClient ,unstable_localLink } from '@trpc/client';import type {AppRouter } from './server';import {appRouter } from './server';constclient =createTRPCClient <AppRouter >({links : [unstable_localLink ({router :appRouter ,createContext : async () => {// Create your context herereturn {};},onError : (opts ) => {// Log errors here, similarly to how you would in an API routeconsole .error ('Error:',opts .error );},}),],});
tsximport {createTRPCClient ,unstable_localLink } from '@trpc/client';import type {AppRouter } from './server';import {appRouter } from './server';constclient =createTRPCClient <AppRouter >({links : [unstable_localLink ({router :appRouter ,createContext : async () => {// Create your context herereturn {};},onError : (opts ) => {// Log errors here, similarly to how you would in an API routeconsole .error ('Error:',opts .error );},}),],});
特性
-
无需 HTTP 开销的直接过程调用
-
完整支持查询(queries)、变更(mutations)和订阅(subscriptions)
-
自动错误处理和转换
-
支持中止信号(abort signals)
-
类型安全的上下文创建
选项
localLink 接受以下配置选项:
tstypeLocalLinkOptions <TRouter extendsAnyRouter > = {router :TRouter ;createContext : () =>Promise <inferRouterContext <TRouter >>;onError ?: (opts :ErrorHandlerOptions <inferRouterContext <TRouter >>) => void;} &TransformerOptions <inferClientTypes <TRouter >>;
tstypeLocalLinkOptions <TRouter extendsAnyRouter > = {router :TRouter ;createContext : () =>Promise <inferRouterContext <TRouter >>;onError ?: (opts :ErrorHandlerOptions <inferRouterContext <TRouter >>) => void;} &TransformerOptions <inferClientTypes <TRouter >>;
router
用于过程调用的 tRPC router 实例。
createContext
为每个过程调用创建上下文的函数。该函数在每个请求时被调用,应返回解析为上下文对象的 Promise。
onError
可选的错误处理函数,在过程调用发生错误时触发。接收错误对象、操作类型、路径、输入参数和上下文。
transformer
用于数据序列化/反序列化的可选输入/输出转换器。
注意事项
-
推荐在需要绕过 HTTP 直接进行过程调用的场景中使用
-
对于大多数客户端应用,应优先使用
httpLink或其他基于 HTTP 的链接 -
支持所有 tRPC 功能(包括查询、变更和订阅)
-
错误处理和转换会自动完成,与基于 HTTP 的链接行为一致