分流链接
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
splitLink 是一个允许根据给定条件分支执行链路链的链接。必须同时提供 true 和 false 两个分支。您可以为每个分支提供单个链接,或通过数组提供多个链接。
需要特别注意:当您为 splitLink 提供执行链接时,splitLink 会基于您传递的链接创建全新的链路链。因此,如果您仅提供单个链接,必须使用终止链接;如果为分支提供多个链接执行,则需要在数组末尾添加终止链接。以下是 splitLink 工作原理的可视化说明:
使用示例
禁用特定请求的批处理
假设您在 tRPC 客户端配置中使用 httpBatchLink 作为终止链接,这意味着所有请求都启用了批处理。但如果需要仅对特定请求禁用批处理,您需要动态切换 tRPC 客户端配置中的终止链接(在 httpLink 和 httpBatchLink 之间),这正是使用 splitLink 的理想场景:
1. 配置客户端 / utils/trpc.ts
client/index.tstsimport {createTRPCProxyClient,httpBatchLink,httpLink,splitLink,} from '@trpc/client';import type { AppRouter } from '../server';const url = `http://localhost:3000`;const client = createTRPCProxyClient<AppRouter>({links: [splitLink({condition(op) {// check for context property `skipBatch`return op.context.skipBatch === true;},// when condition is true, use normal requesttrue: httpLink({url,}),// when condition is false, use batchingfalse: httpBatchLink({url,}),}),],});
client/index.tstsimport {createTRPCProxyClient,httpBatchLink,httpLink,splitLink,} from '@trpc/client';import type { AppRouter } from '../server';const url = `http://localhost:3000`;const client = createTRPCProxyClient<AppRouter>({links: [splitLink({condition(op) {// check for context property `skipBatch`return op.context.skipBatch === true;},// when condition is true, use normal requesttrue: httpLink({url,}),// when condition is false, use batchingfalse: httpBatchLink({url,}),}),],});
2. 执行无批处理的请求
client.tstsconst postResult = proxy.posts.query(null, {context: {skipBatch: true,},});
client.tstsconst postResult = proxy.posts.query(null, {context: {skipBatch: true,},});
或:
MyComponent.tsxtsxexport function MyComponent() {const postsQuery = proxy.posts.useQuery(undefined, {trpc: {context: {skipBatch: true,},}});return (<pre>{JSON.stringify(postsQuery.data ?? null, null, 4)}</pre>)})
MyComponent.tsxtsxexport function MyComponent() {const postsQuery = proxy.posts.useQuery(undefined, {trpc: {context: {skipBatch: true,},}});return (<pre>{JSON.stringify(postsQuery.data ?? null, null, 4)}</pre>)})
splitLink 配置项
splitLink 函数接收包含三个字段的配置对象:condition、true 和 false。
tsfunction splitLink<TRouter extends AnyRouter = AnyRouter>(opts: {condition: (op: Operation) => boolean;/*** The link to execute next if the test function returns `true`.*/true: TRPCLink<TRouter> | TRPCLink<TRouter>[];/*** The link to execute next if the test function returns `false`.*/false: TRPCLink<TRouter> | TRPCLink<TRouter>[];}) => TRPCLink<TRouter>
tsfunction splitLink<TRouter extends AnyRouter = AnyRouter>(opts: {condition: (op: Operation) => boolean;/*** The link to execute next if the test function returns `true`.*/true: TRPCLink<TRouter> | TRPCLink<TRouter>[];/*** The link to execute next if the test function returns `false`.*/false: TRPCLink<TRouter> | TRPCLink<TRouter>[];}) => TRPCLink<TRouter>
参考文档
您可以在 GitHub 查看该链接的源代码。