拆分链接
splitLink 是一个链接,它允许您根据给定条件分支链接链的执行。true 和 false 分支都需要。您可以为每个分支提供一个链接,也可以通过数组提供多个链接。
需要注意的是,当您提供链接供 splitLink 执行时,splitLink 将根据您传递的链接创建一个全新的链接链。因此,如果您只提供一个链接,则需要使用 终止链接,或者如果您提供多个链接要在分支上执行,则在数组末尾添加终止链接。以下是 splitLink 工作方式的直观表示
使用示例
为某些请求禁用批处理
假设您正在使用 httpBatchLink 作为 tRPC 客户端配置中的终止链接。这意味着在每个请求中都启用了请求批处理。但是,如果您需要仅为某些请求禁用批处理,则需要在 tRPC 客户端配置中动态更改终止链接,在 httpLink 和 httpBatchLink 之间切换。这是一个使用 splitLink 的绝佳机会
1. 配置客户端 / utils/trpc.ts
client/index.tstsimport {createTRPCClient,httpBatchLink,httpLink,splitLink,} from '@trpc/client';import type { AppRouter } from '../server';const url = `https://:3000`;const client = createTRPCClient<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 {createTRPCClient,httpBatchLink,httpLink,splitLink,} from '@trpc/client';import type { AppRouter } from '../server';const url = `https://:3000`;const client = createTRPCClient<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 上查看此链接的源代码。