重试链接
retryLink
是一个链接,允许你在 tRPC 客户端中重试失败的操作。它提供了一种可自定义的方式来处理瞬态错误,例如网络故障或服务器错误,通过根据指定条件自动重试失败的请求。
¥retryLink
is a link that allows you to retry failed operations in your tRPC client. It provides a customizable way to handle transient errors, such as network failures or server errors, by automatically retrying the failed requests based on specified conditions.
如果你使用 @trpc/react-query
,则通常不需要此链接,因为它内置于 useQuery()
和 @tanstack/react-query
中的 useMutation()
钩子中。
¥If you use @trpc/react-query
you will generally not need this link as it's built into the useQuery()
and the useMutation()
hooks from @tanstack/react-query
.
用法
¥Usage
你可以在创建 tRPC 客户端时导入并将 retryLink
添加到 links
数组中。根据你的要求,此链接可以放在设置中的其他链接之前或之后。
¥You can import and add the retryLink
to the links
array when creating your tRPC client. This link can be placed before or after other links in your setup, depending on your requirements.
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-500sreturn false;}if (opts.op.type !== 'query') {// Only retry queriesreturn false;}// Retry up to 3 timesreturn 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-500sreturn false;}if (opts.op.type !== 'query') {// Only retry queriesreturn false;}// Retry up to 3 timesreturn 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',}),],});
在上面的示例中,我们在 httpBatchLink
之前添加了 retryLink
。默认情况下,retryLink
将:
¥In the example above, we add the retryLink
before the httpBatchLink
. By default, retryLink
will:
-
如果错误是状态代码为 500 的
TRPCClientError
,或者我们无法获得有效的 TRPC 错误,则重试请求。¥Retry the request if the error is a
TRPCClientError
with a status code of 500 or if we couldn't get a valid TRPC error. -
重试请求最多 3 次。
¥Retry the request up to 3 times.
你可以通过提供自定义 retry
函数来自定义重试逻辑。
¥You can customize the retry logic by providing a custom retry
function.
选项
¥Options
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;}
处理 tracked() 事件
¥Handling tracked() events
当使用 retryLink
和使用 tracked()
的订阅时,重试时链接将自动包含最后一个已知事件 ID。这可确保当订阅重新连接时,它可以从中断的地方恢复,而不会遗漏任何事件。
¥When using retryLink
with subscriptions that use tracked()
, the link will automatically include the last known event ID when retrying. This ensures that when a subscription reconnects, it can resume from where it left off without missing any events.
例如,如果你将服务器发送事件 (SSE) 与 httpSubscriptionLink
一起使用,则当发生像 401 Unauthorized
这样的错误时,retryLink
将自动处理使用最后一个事件 ID 的重新连接。
¥For example, if you're using Server-sent Events (SSE) with httpSubscriptionLink
, the retryLink
will automatically handle reconnecting with the last event ID when errors like 401 Unauthorized
occur.