HTTP 배치 스트림 링크
이 페이지는 PageTurner AI로 번역되었습니다(베타). 프로젝트 공식 승인을 받지 않았습니다. 오류를 발견하셨나요? 문제 신고 →
httpBatchStreamLink는 개별 tRPC 작업 배열을 단일 tRPC 프로시저로 전송되는 하나의 HTTP 요청으로 일괄 처리하는 종단 링크입니다(httpBatchLink와 동등). 단, 배치의 모든 응답이 준비될 때까지 기다리지 않고 데이터가 사용 가능해지는 즉시 응답을 스트리밍합니다.
옵션
옵션은 httpBatchLink options과 동일하며, 다음과 같은 추가 사항이 있습니다:
| Option | Type | Default | Description |
|---|---|---|---|
streamHeader | 'trpc-accept' | 'accept' | 'trpc-accept' | Which header to use to signal the server that the client wants a streaming response. 'accept' uses the standard Accept header instead of the custom trpc-accept header, which can avoid CORS preflight for cross-origin streaming queries since Accept is a CORS-safelisted header. |
사용법
모든 사용법과 옵션은
httpBatchLink와 동일합니다.
프로시저 내에서 응답 헤더(쿠키 포함)를 변경/설정해야 하는 경우 반드시 httpBatchLink를 대신 사용하세요! 이는 httpBatchStreamLink가 스트림 시작 후 헤더 설정을 지원하지 않기 때문입니다. 자세히 보기.
다음과 같이 httpBatchStreamLink를 가져와 links 배열에 추가할 수 있습니다:
client/index.tstsimport {createTRPCClient ,httpBatchStreamLink } from '@trpc/client';import type {AppRouter } from './server';constclient =createTRPCClient <AppRouter >({links : [httpBatchStreamLink ({url : 'http://localhost:3000',}),],});
client/index.tstsimport {createTRPCClient ,httpBatchStreamLink } from '@trpc/client';import type {AppRouter } from './server';constclient =createTRPCClient <AppRouter >({links : [httpBatchStreamLink ({url : 'http://localhost:3000',}),],});
이후 모든 프로시저를 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의 동작은 모든 요청이 완료될 때까지 응답 전송을 대기하는 것입니다. 응답이 준비되는 즉시 전송하려면 httpBatchStreamLink를 대신 사용할 수 있습니다. 이는 장기 실행 요청에 유용합니다.
client/index.tstsimport {createTRPCClient ,httpBatchStreamLink } from '@trpc/client';import type {AppRouter } from './server';constclient =createTRPCClient <AppRouter >({links : [httpBatchStreamLink ({url : 'http://localhost:3000',}),],});
client/index.tstsimport {createTRPCClient ,httpBatchStreamLink } from '@trpc/client';import type {AppRouter } from './server';constclient =createTRPCClient <AppRouter >({links : [httpBatchStreamLink ({url : 'http://localhost:3000',}),],});
일반적인 httpBatchLink와 비교하여 httpBatchStreamLink는 다음과 같은 특징을 가집니다:
-
요청이
trpc-accept: application/jsonl헤더와 함께 전송되도록 합니다(또는streamHeader: 'accept'사용 시Accept: application/jsonl) -
응답을
transfer-encoding: chunked및content-type: application/jsonl과 함께 전송 -
responseMeta에 전달되는 인수 객체에서data키 제거 (스트리밍 응답 시 데이터가 사용 가능해지기 전에 헤더가 전송되기 때문)
비동기 생성자와 지연된 프로미스
tRPC.io 홈페이지에서 직접 체험해 볼 수 있습니다: https://trpc.io/?try=minimal#try-it-out
tsimport {createTRPCClien t,httpB atchStreamLink } from '@trpc/client';import type { AppRouter } from './server';const trpc = createTRPCClient<AppRouter>({links: [httpBatchStreamLink({ url:'http ://localh ost:3000',}),],});const iterable = await trpc.examples.iterable.query();for await (const value of iterable) {console.log('Iterable:', value);}
tsimport {createTRPCClien t,httpB atchStreamLink } from '@trpc/client';import type { AppRouter } from './server';const trpc = createTRPCClient<AppRouter>({links: [httpBatchStreamLink({ url:'http ://localh ost:3000',}),],});const iterable = await trpc.examples.iterable.query();for await (const value of iterable) {console.log('Iterable:', value);}
호환성 (클라이언트 측)
브라우저
브라우저 지원은 fetch 지원과 동일해야 합니다.
Node.js / Deno
브라우저 이외의 런타임에서는 fetch 구현이 스트리밍을 지원해야 합니다. 즉, await fetch(...)로 얻은 응답은 ReadableStream<Uint8Array> | NodeJS.ReadableStream 유형의 body 속성을 가져야 합니다:
-
response.body.getReader가ReadableStreamDefaultReader<Uint8Array>객체를 반환하는 함수이거나 -
response.body가Uint8ArrayBuffer이어야 함
여기에는 undici, node-fetch, 네이티브 Node.js fetch 구현 및 WebAPI fetch 구현(브라우저)에 대한 지원이 포함됩니다.
React Native
스트림 수신은 TextDecoder 및 TextDecoderStream API에 의존하는데, 이들은 React Native에서 사용할 수 없습니다. 주의할 점은 TextDecoderStream 폴리필이 자동으로 ReadableStream과 WritableStream을 폴리필하지 않는다면 이들도 별도로 폴리필해야 한다는 것입니다. 스트리밍을 활성화하려면 이를 반드시 폴리필해야 합니다.
또한 httpBatchStreamLink 설정 옵션에서 기본 fetch를 재정의해야 합니다. 아래 예시에서는 fetch 구현체로 Expo fetch 패키지를 사용합니다.
tsimport { httpBatchStreamLink } from '@trpc/client';httpBatchStreamLink({fetch: (url, opts) =>fetch(url, {...opts,reactNative: { textStreaming: true },}),url: 'http://localhost:3000',});
tsimport { httpBatchStreamLink } from '@trpc/client';httpBatchStreamLink({fetch: (url, opts) =>fetch(url, {...opts,reactNative: { textStreaming: true },}),url: 'http://localhost:3000',});
호환성 (서버 측)
httpBatchStreamLink는 인프라가 스트리밍 응답을 지원하도록 설정된 경우에만 AWS Lambda에서 지원됩니다. 그렇지 않으면 이 링크는 일반 httpBatchLink처럼 동작합니다.
streams_enable_constructors 기능 플래그를 통해 ReadableStream API를 활성화해야 합니다.
참조
이 링크의 소스 코드는 GitHub에서 확인할 수 있습니다.
연결 유지를 위한 ping 옵션 설정
루트 설정 시 jsonl 옵션을 전달하여 연결 유지를 위한 ping 설정을 구성할 수 있습니다.
tsimport {initTRPC } from '@trpc/server';constt =initTRPC .create ({jsonl : {pingMs : 1000,},});
tsimport {initTRPC } from '@trpc/server';constt =initTRPC .create ({jsonl : {pingMs : 1000,},});