HTTP 배치 링크
이 페이지는 PageTurner AI로 번역되었습니다(베타). 프로젝트 공식 승인을 받지 않았습니다. 오류를 발견하셨나요? 문제 신고 →
httpBatchLink는 개별 tRPC 작업 배열을 단일 tRPC 프로시저로 전송되는 단일 HTTP 요청으로 배칭하는 종단 링크입니다.
사용법
다음과 같이 httpBatchLink를 가져와 links 배열에 추가할 수 있습니다:
client/index.tstsimport {createTRPCClient ,httpBatchLink } from '@trpc/client';import type {AppRouter } from './server';constclient =createTRPCClient <AppRouter >({links : [httpBatchLink ({url : 'http://localhost:3000',// transformer,}),],});
client/index.tstsimport {createTRPCClient ,httpBatchLink } from '@trpc/client';import type {AppRouter } from './server';constclient =createTRPCClient <AppRouter >({links : [httpBatchLink ({url : 'http://localhost:3000',// transformer,}),],});
이후 모든 프로시저를 Promise.all로 설정하면 일괄 처리를 활용할 수 있습니다. 아래 코드는 정확히 하나의 HTTP 요청을 생성하고 서버에서 정확히 하나의 데이터베이스 쿼리를 실행합니다:
tsconstsomePosts = awaitPromise .all ([trpc .post .byId .query (1),trpc .post .byId .query (2),trpc .post .byId .query (3),]);
tsconstsomePosts = awaitPromise .all ([trpc .post .byId .query (1),trpc .post .byId .query (2),trpc .post .byId .query (3),]);
httpBatchLink 옵션
httpBatchLink 함수는 HTTPBatchLinkOptions 형태의 옵션 객체를 받습니다.
tsexport interfaceHTTPBatchLinkOptions extendsHTTPLinkOptions {/*** Maximum length of HTTP URL allowed before operations are split into multiple requests* @default Infinity*/maxURLLength ?: number;/*** Maximum number of operations allowed in a single batch request* @default Infinity*/maxItems ?: number;}export interfaceHTTPLinkOptions {url : string |URL ;/*** Add ponyfill for fetch*/fetch ?: typeoffetch ;/*** Data transformer* @see https://trpc.io/docs/server/data-transformers**/transformer ?:DataTransformerOptions ;/*** Headers to be set on outgoing requests or a callback that of said headers* @see https://trpc.io/docs/client/headers*/headers ?:|HTTPHeaders | ((opts : {opList :NonEmptyArray <Operation > }) =>HTTPHeaders |Promise <HTTPHeaders >);}
tsexport interfaceHTTPBatchLinkOptions extendsHTTPLinkOptions {/*** Maximum length of HTTP URL allowed before operations are split into multiple requests* @default Infinity*/maxURLLength ?: number;/*** Maximum number of operations allowed in a single batch request* @default Infinity*/maxItems ?: number;}export interfaceHTTPLinkOptions {url : string |URL ;/*** Add ponyfill for fetch*/fetch ?: typeoffetch ;/*** Data transformer* @see https://trpc.io/docs/server/data-transformers**/transformer ?:DataTransformerOptions ;/*** Headers to be set on outgoing requests or a callback that of said headers* @see https://trpc.io/docs/client/headers*/headers ?:|HTTPHeaders | ((opts : {opList :NonEmptyArray <Operation > }) =>HTTPHeaders |Promise <HTTPHeaders >);}
최대 URL 길이 설정
배치 요청 전송 시 URL이 너무 길어져 413 Payload Too Large, 414 URI Too Long, 404 Not Found 같은 HTTP 오류가 발생할 수 있습니다. maxURLLength 옵션은 배치로 함께 전송될 수 있는 요청 수를 제한합니다.
client/index.tstsimport {createTRPCClient ,httpBatchLink } from '@trpc/client';import type {AppRouter } from './server';constclient =createTRPCClient <AppRouter >({links : [httpBatchLink ({url : 'http://localhost:3000',maxURLLength : 2083, // a suitable size// alternatively, you can make all RPC-calls to be called with POST// methodOverride: 'POST',}),],});
client/index.tstsimport {createTRPCClient ,httpBatchLink } from '@trpc/client';import type {AppRouter } from './server';constclient =createTRPCClient <AppRouter >({links : [httpBatchLink ({url : 'http://localhost:3000',maxURLLength : 2083, // a suitable size// alternatively, you can make all RPC-calls to be called with POST// methodOverride: 'POST',}),],});
배치 크기 제한
1. 서버에 최대 배치 크기 설정:
maxBatchSize는 단일 배치 요청으로 전송될 수 있는 작업 수를 제한합니다. 이 한도를 초과하는 요청은 400 Bad Request 오류로 거부됩니다. 이 설정은 모든 tRPC 어댑터에 전달할 수 있습니다.
server.tstsimport { createHTTPServer } from '@trpc/server/adapters/standalone';createHTTPServer({maxBatchSize: 10,});
server.tstsimport { createHTTPServer } from '@trpc/server/adapters/standalone';createHTTPServer({maxBatchSize: 10,});
또는 예를 들어 Next.js를 사용하는 경우:
pages/api/trpc/[trpc].tstsexport default trpcNext.createNextApiHandler({maxBatchSize: 10,});
pages/api/trpc/[trpc].tstsexport default trpcNext.createNextApiHandler({maxBatchSize: 10,});
2. 클라이언트에 일치하는 제한 설정:
클라이언트가 서버의 한도를 초과하지 않도록 배치 링크의 maxItems 옵션을 사용하세요. 이렇게 하면 대규모 배치를 자동으로 여러 HTTP 요청으로 분할합니다.
client/index.tstsimport { createTRPCClient, httpBatchLink } from '@trpc/client';import type { AppRouter } from '../server';const client = createTRPCClient<AppRouter>({links: [httpBatchLink({url: 'http://localhost:3000',// 👇 should be the same or lower than the server's maxBatchSizemaxItems: 10,}),],});
client/index.tstsimport { createTRPCClient, httpBatchLink } from '@trpc/client';import type { AppRouter } from '../server';const client = createTRPCClient<AppRouter>({links: [httpBatchLink({url: 'http://localhost:3000',// 👇 should be the same or lower than the server's maxBatchSizemaxItems: 10,}),],});
요청 배칭 비활성화
1. 서버에서 batching 비활성화:
server.tstsimport {createHTTPServer } from '@trpc/server/adapters/standalone';import {appRouter } from './router';createHTTPServer ({router :appRouter ,// 👇 disable batchingallowBatching : false,});
server.tstsimport {createHTTPServer } from '@trpc/server/adapters/standalone';import {appRouter } from './router';createHTTPServer ({router :appRouter ,// 👇 disable batchingallowBatching : false,});
또는 Next.js를 사용하는 경우:
pages/api/trpc/[trpc].tstsimport {createNextApiHandler } from '@trpc/server/adapters/next';import {appRouter } from '../../../router';export defaultcreateNextApiHandler ({router :appRouter ,// 👇 disable batchingallowBatching : false,});
pages/api/trpc/[trpc].tstsimport {createNextApiHandler } from '@trpc/server/adapters/next';import {appRouter } from '../../../router';export defaultcreateNextApiHandler ({router :appRouter ,// 👇 disable batchingallowBatching : false,});
2. tRPC 클라이언트에서 httpBatchLink를 httpLink로 교체
client/index.tstsimport {createTRPCClient ,httpLink } from '@trpc/client';import type {AppRouter } from './server';constclient =createTRPCClient <AppRouter >({links : [httpLink ({url : 'http://localhost:3000',}),],});
client/index.tstsimport {createTRPCClient ,httpLink } from '@trpc/client';import type {AppRouter } from './server';constclient =createTRPCClient <AppRouter >({links : [httpLink ({url : 'http://localhost:3000',}),],});
또는 Next.js를 사용하는 경우:
utils/trpc.tstsximport type {AppRouter } from '../server';import {httpLink } from '@trpc/client';import {createTRPCNext } from '@trpc/next';export consttrpc =createTRPCNext <AppRouter >({config () {return {links : [httpLink ({url : '/api/trpc',}),],};},});
utils/trpc.tstsximport type {AppRouter } from '../server';import {httpLink } from '@trpc/client';import {createTRPCNext } from '@trpc/next';export consttrpc =createTRPCNext <AppRouter >({config () {return {links : [httpLink ({url : '/api/trpc',}),],};},});