본문 바로가기
버전: 11.x

분할 링크

비공식 베타 번역

이 페이지는 PageTurner AI로 번역되었습니다(베타). 프로젝트 공식 승인을 받지 않았습니다. 오류를 발견하셨나요? 문제 신고 →

splitLink는 주어진 조건에 따라 링크 체인의 실행 경로를 분기할 수 있는 링크입니다. truefalse 두 가지 분기 모두 필수로 제공되어야 합니다. 각 분기에 단일 링크를 제공하거나 배열을 통해 여러 링크를 제공할 수 있습니다.

중요한 점은 splitLink가 실행할 링크를 제공할 때, splitLink가 전달한 링크들을 기반으로 완전히 새로운 링크 체인을 생성한다는 것입니다. 따라서 단일 링크만 제공하는 경우 종료 링크를 사용해야 하며, 분기에서 실행될 여러 링크를 제공하는 경우 배열 끝에 종료 링크를 추가해야 합니다. 다음은 splitLink의 동작 방식을 시각적으로 표현한 것입니다:

tRPC ClientOperationLinkLinksplitLinkInitiatedCompleteddowndownupupTerminating LinkRequestResponseRequesttRPC Serverpasses condition?LinkTerminating LinkLinktrueBranchfalseBranchdownupResponseYESNOdownupdownup

사용 예시

특정 요청에 대한 배칭 비활성화

tRPC 클라이언트 설정에서 종료 링크로 httpBatchLink를 사용하고 있다고 가정해 보겠습니다. 이는 모든 요청에서 배칭이 활성화됨을 의미합니다. 하지만 특정 요청에 대해서만 배칭을 비활성화해야 하는 경우, tRPC 클라이언트 설정에서 종료 링크를 httpLinkhttpBatchLink 사이에서 동적으로 전환해야 합니다. 이때 splitLink를 사용하기에 완벽한 시나리오입니다:

1. 클라이언트 구성 / 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. 배칭 없이 요청 수행

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

또는:

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>
)
})

splitLink 함수는 condition, true, 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>

참조

이 링크의 소스 코드는 GitHub에서 확인할 수 있습니다.