Saltar al contenido principal
Versión: 11.x

Enlace de División

Traducción Beta No Oficial

Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →

splitLink es un enlace que te permite bifurcar la ejecución de tu cadena de enlaces según una condición dada. Ambas ramas (true y false) son obligatorias. Puedes proporcionar un solo enlace o múltiples enlaces por rama mediante un arreglo.

Es importante destacar que cuando proporcionas enlaces para que splitLink los ejecute, splitLink creará una nueva cadena de enlaces completa basada en los enlaces que pasaste. Por lo tanto, debes usar un enlace de terminación si solo proporcionas un enlace, o agregar el enlace de terminación al final del arreglo si proporcionas múltiples enlaces para ejecutar en una rama. Aquí tienes una representación visual de cómo funciona splitLink:

tRPC ClientOperationLinkLinksplitLinkInitiatedCompleteddowndownupupTerminating LinkRequestResponseRequesttRPC Serverpasses condition?LinkTerminating LinkLinktrueBranchfalseBranchdownupResponseYESNOdownupdownup

Ejemplo de Uso

Desactivar el procesamiento por lotes para ciertas solicitudes

Supongamos que usas httpBatchLink como enlace de terminación en tu configuración de cliente tRPC. Esto significa que el procesamiento por lotes está activado en todas las solicitudes. Sin embargo, si necesitas desactivar el procesamiento por lotes solo para ciertas solicitudes, deberás cambiar dinámicamente el enlace de terminación en tu configuración de cliente tRPC entre httpLink y httpBatchLink. Esta es una oportunidad perfecta para usar splitLink:

1. Configurar cliente / utils/trpc.ts

client/index.ts
ts
import {
createTRPCClient,
httpBatchLink,
httpLink,
splitLink,
} from '@trpc/client';
import type { AppRouter } from '../server';
const url = `http://localhost:3000`;
const client = createTRPCClient<AppRouter>({
links: [
splitLink({
condition(op) {
// check for context property `skipBatch`
return Boolean(op.context.skipBatch);
},
// when condition is true, use normal request
true: httpLink({
url,
}),
// when condition is false, use batching
false: httpBatchLink({
url,
}),
}),
],
});
client/index.ts
ts
import {
createTRPCClient,
httpBatchLink,
httpLink,
splitLink,
} from '@trpc/client';
import type { AppRouter } from '../server';
const url = `http://localhost:3000`;
const client = createTRPCClient<AppRouter>({
links: [
splitLink({
condition(op) {
// check for context property `skipBatch`
return Boolean(op.context.skipBatch);
},
// when condition is true, use normal request
true: httpLink({
url,
}),
// when condition is false, use batching
false: httpBatchLink({
url,
}),
}),
],
});

2. Realizar solicitud sin procesamiento por lotes

client.ts
ts
const postResult = proxy.posts.query(null, {
context: {
skipBatch: true,
},
});
client.ts
ts
const postResult = proxy.posts.query(null, {
context: {
skipBatch: true,
},
});

o:

MyComponent.tsx
tsx
export function MyComponent() {
const postsQuery = proxy.posts.useQuery(undefined, {
trpc: {
context: {
skipBatch: true,
},
}
});
return (
<pre>{JSON.stringify(postsQuery.data ?? null, null, 4)}</pre>
)
})
MyComponent.tsx
tsx
export function MyComponent() {
const postsQuery = proxy.posts.useQuery(undefined, {
trpc: {
context: {
skipBatch: true,
},
}
});
return (
<pre>{JSON.stringify(postsQuery.data ?? null, null, 4)}</pre>
)
})

La función splitLink recibe un objeto de opciones con tres campos: condition, true y false.

ts
function 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>
ts
function 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>

Referencia

Puedes consultar el código fuente de este enlace en GitHub.