재시도 링크
이 페이지는 PageTurner AI로 번역되었습니다(베타). 프로젝트 공식 승인을 받지 않았습니다. 오류를 발견하셨나요? 문제 신고 →
retryLink는 tRPC 클라이언트에서 실패한 작업을 재시도할 수 있게 해주는 링크입니다. 네트워크 장애나 서버 오류와 같은 일시적인 오류를 처리하기 위한 사용자 정의 가능한 방법을 제공하며, 지정된 조건에 따라 실패한 요청을 자동으로 재시도합니다.
@trpc/react-query를 사용하는 경우 일반적으로 이 링크가 필요하지 않습니다. @tanstack/react-query의 useQuery() 및 useMutation() 훅에 이미 내장되어 있기 때문입니다.
사용법
tRPC 클라이언트를 생성할 때 retryLink를 가져와 links 배열에 추가할 수 있습니다. 요구 사항에 따라 이 링크를 다른 링크 앞이나 뒤에 배치할 수 있습니다.
tsimport { 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',}),],});
tsimport { 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',}),],});
위 예시에서는 retryLink를 httpBatchLink 앞에 추가했습니다. 기본적으로 retryLink는 다음을 수행합니다:
-
오류가 상태 코드 500인
TRPCClientError이거나 유효한 TRPC 오류를 가져올 수 없는 경우 요청 재시도 -
최대 3회까지 요청 재시도
사용자 정의 retry 함수를 제공하여 재시도 로직을 커스터마이징할 수 있습니다.
옵션
tsinterface 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;}
tsinterface 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() 이벤트 처리
tracked()를 사용하는 구독과 함께 retryLink를 사용할 때, 링크는 재시도 시 마지막으로 알려진 이벤트 ID를 자동으로 포함합니다. 이로 인해 구독이 다시 연결될 때 중단된 지점부터 이벤트를 놓치지 않고 재개할 수 있습니다.
예를 들어 httpSubscriptionLink와 함께 Server-sent Events(SSE)를 사용하는 경우, 401 Unauthorized와 같은 오류가 발생하면 retryLink가 마지막 이벤트 ID로 자동 재연결을 처리합니다.