HTTP 배치 스트림 링크
httpBatchStreamLink는 여러 tRPC 작업을 하나의 HTTP 요청으로 배치해 단일 tRPC 프로시저로 보내는 종단 링크입니다(httpBatchLink와 동일). 다만 배치의 모든 응답이 준비될 때까지 기다리지 않고, 데이터가 준비되는 즉시 각 응답을 스트리밍합니다.
옵션
옵션은 httpBatchLink options와 동일하며, 다음 항목이 추가됩니다:
| 옵션 | 타입 | 기본값 | 설명 |
|---|---|---|---|
streamHeader | 'trpc-accept' | 'accept' | 'trpc-accept' | 클라이언트가 스트리밍 응답을 원한다는 것을 서버에 알리기 위해 사용할 헤더입니다. 'accept'는 사용자 정의 trpc-accept 헤더 대신 표준 Accept 헤더를 사용하므로, Accept가 CORS 안전 목록에 포함된 헤더이기 때문에 교차 출처 스트리밍 쿼리에 대한 CORS 사전 요청(preflight)을 피할 수 있습니다. |
사용법
모든 사용법과 옵션은
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 구현, 브라우저의 Web API fetch 구현이 포함됩니다.
React Native
스트림 수신은 React Native에서 사용할 수 없는 TextDecoder 및 TextDecoderStream API에 의존합니다. 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처럼 동작합니다.
ReadableStream API를 활성화하려면 기능 플래그를 설정해야 합니다: streams_enable_constructors.
참고
이 링크의 소스 코드를 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,},});