Saltar al contenido principal
Versión: 11.x

Enlace de Reintento

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 →

retryLink es un enlace que te permite reintentar operaciones fallidas en tu cliente tRPC. Proporciona una forma personalizable de manejar errores transitorios, como fallos de red o errores del servidor, al reintentar automáticamente las solicitudes fallidas según condiciones especificadas.

consejo

Si usas @trpc/react-query, generalmente no necesitarás este enlace, ya que está integrado en los hooks useQuery() y useMutation() de @tanstack/react-query.

Uso

Puedes importar y agregar retryLink al array links al crear tu cliente tRPC. Este enlace puede colocarse antes o después de otros enlaces en tu configuración, según tus necesidades.

ts
import { createTRPCClient, retryLink } from '@trpc/client';
const client = createTRPCClient<AppRouter>({
links: [
retryLink({
retry(opts) {
if (
opts.error.data &&
opts.error.data.code !== 'INTERNAL_SERVER_ERROR'
) {
// Don't retry on non-500s
return false;
}
if (opts.op.type !== 'query') {
// Only retry queries
return false;
}
// Retry up to 3 times
return opts.attempts <= 3;
},
// Double every attempt, with max of 30 seconds (starting at 1 second)
retryDelayMs: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
}),
httpBatchLink({
url: 'http://localhost:3000',
}),
],
});
ts
import { createTRPCClient, retryLink } from '@trpc/client';
const client = createTRPCClient<AppRouter>({
links: [
retryLink({
retry(opts) {
if (
opts.error.data &&
opts.error.data.code !== 'INTERNAL_SERVER_ERROR'
) {
// Don't retry on non-500s
return false;
}
if (opts.op.type !== 'query') {
// Only retry queries
return false;
}
// Retry up to 3 times
return opts.attempts <= 3;
},
// Double every attempt, with max of 30 seconds (starting at 1 second)
retryDelayMs: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
}),
httpBatchLink({
url: 'http://localhost:3000',
}),
],
});

En el ejemplo anterior, agregamos retryLink antes de httpBatchLink. Por defecto, retryLink hará lo siguiente:

  • Reintentará la solicitud si el error es un TRPCClientError con código de estado 500 o si no se pudo obtener un error TRPC válido.

  • Reintentará la solicitud hasta 3 veces.

Puedes personalizar la lógica de reintento proporcionando una función retry personalizada.

Opciones

ts
interface RetryLinkOptions<TInferrable extends InferrableClientTypes> {
/**
* The retry function
*/
retry: (opts: RetryFnOptions<TInferrable>) => boolean;
/**
* The delay between retries in ms (defaults to 0)
*/
retryDelayMs?: (attempt: number) => number;
}
interface RetryFnOptions<TInferrable extends InferrableClientTypes> {
/**
* The operation that failed
*/
op: Operation;
/**
* The error that occurred
*/
error: TRPCClientError<TInferrable>;
/**
* The number of attempts that have been made (including the first call)
*/
attempts: number;
}
ts
interface RetryLinkOptions<TInferrable extends InferrableClientTypes> {
/**
* The retry function
*/
retry: (opts: RetryFnOptions<TInferrable>) => boolean;
/**
* The delay between retries in ms (defaults to 0)
*/
retryDelayMs?: (attempt: number) => number;
}
interface RetryFnOptions<TInferrable extends InferrableClientTypes> {
/**
* The operation that failed
*/
op: Operation;
/**
* The error that occurred
*/
error: TRPCClientError<TInferrable>;
/**
* The number of attempts that have been made (including the first call)
*/
attempts: number;
}

Manejo de eventos tracked()

Al usar retryLink con suscripciones que emplean tracked(), el enlace incluirá automáticamente el último ID de evento conocido al reintentar. Esto garantiza que cuando una suscripción se reconecte, pueda continuar desde donde lo dejó sin perderse eventos.

Por ejemplo, si usas Server-sent Events (SSE) con httpSubscriptionLink, retryLink manejará automáticamente la reconexión con el último ID de evento cuando ocurran errores como 401 Unauthorized.