HTTP 배치 스트림 링크
이 페이지는 PageTurner AI로 번역되었습니다(베타). 프로젝트 공식 승인을 받지 않았습니다. 오류를 발견하셨나요? 문제 신고 →
unstable_httpBatchStreamLink는 개별 tRPC 작업 배열을 단일 tRPC 프로시저로 전송되는 하나의 HTTP 요청으로 일괄 처리하는 종단 링크입니다(httpBatchLink와 동등). 하지만 배치된 모든 응답이 준비될 때까지 기다리지 않고 데이터가 사용 가능해지는 즉시 응답을 스트리밍합니다.
이 API는 새로운 기능이므로 unstable_ 접두사를 붙였지만 안전하게 사용하셔도 됩니다! 자세히 알아보기.
사용법
모든 사용법과 옵션은
httpBatchLink와 동일합니다.
프로시저 내에서 응답 헤더(쿠키 포함)를 변경/설정해야 하는 경우, 반드시 httpBatchLink를 대신 사용하세요! 이는 unstable_httpBatchStreamLink가 스트리밍이 시작된 후에는 헤더 설정을 지원하지 않기 때문입니다. 자세히 알아보기.
다음과 같이 httpBatchStreamLink를 가져와 links 배열에 추가할 수 있습니다:
client/index.tstsimport { createTRPCProxyClient, httpBatchStreamLink } from '@trpc/client';import type { AppRouter } from '../server';const client = createTRPCProxyClient<AppRouter>({links: [httpBatchStreamLink({url: 'http://localhost:3000',}),],});
client/index.tstsimport { createTRPCProxyClient, httpBatchStreamLink } from '@trpc/client';import type { AppRouter } from '../server';const client = createTRPCProxyClient<AppRouter>({links: [httpBatchStreamLink({url: 'http://localhost:3000',}),],});
이후 모든 프로시저를 Promise.all로 설정하면 일괄 처리를 활용할 수 있습니다. 아래 코드는 정확히 하나의 HTTP 요청을 생성하고 서버에서 정확히 하나의 데이터베이스 쿼리를 실행합니다:
tsconst somePosts = await Promise.all([trpc.post.byId.query(1),trpc.post.byId.query(2),trpc.post.byId.query(3),]);
tsconst somePosts = await Promise.all([trpc.post.byId.query(1),trpc.post.byId.query(2),trpc.post.byId.query(3),]);
스트리밍 모드
⚠️ 이 링크는 불안정(unstable)하며 추후 변경될 수 있습니다.
요청을 일괄 처리할 때 일반적인 httpBatchLink의 동작은 모든 요청이 완료될 때까지 응답 전송을 대기하는 것입니다. 응답이 준비되는 즉시 전송하려면 httpBatchStreamLink를 대신 사용할 수 있습니다. 이는 장기 실행 요청에 유용합니다.
client/index.tstsimport {createTRPCProxyClient,unstable_httpBatchStreamLink,} from '@trpc/client';import type { AppRouter } from '../server';const client = createTRPCProxyClient<AppRouter>({links: [unstable_httpBatchStreamLink({url: 'http://localhost:3000',}),],});
client/index.tstsimport {createTRPCProxyClient,unstable_httpBatchStreamLink,} from '@trpc/client';import type { AppRouter } from '../server';const client = createTRPCProxyClient<AppRouter>({links: [unstable_httpBatchStreamLink({url: 'http://localhost:3000',}),],});
일반 httpBatchLink와 비교하여 unstable_httpBatchStreamLink는 다음과 같은 차이가 있습니다:
-
Trpc-Batch-Mode: stream헤더와 함께 요청을 전송합니다 -
Transfer-Encoding: chunked및Vary: trpc-batch-mode헤더와 함께 응답을 전송합니다 -
responseMeta에 전달되는 인수 객체에서data키 제거 (스트리밍 응답 시 데이터가 사용 가능해지기 전에 헤더가 전송되기 때문)
호환성 (클라이언트 측)
브라우저
브라우저 지원은 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 API에 의존하는데, 이 API는 React Native에서 사용할 수 없습니다. 그래도 스트리밍을 활성화하려면 폴리필(polyfill)을 사용하여 httpBatchStreamLink 옵션에 전달하면 됩니다:
tsunstable_httpBatchStreamLink({url: 'http://localhost:3000',textDecoder: new TextDecoder(),// ^? textDecoder: { decode: (input: Uint8Array) => string }});
tsunstable_httpBatchStreamLink({url: 'http://localhost:3000',textDecoder: new TextDecoder(),// ^? textDecoder: { decode: (input: Uint8Array) => string }});
호환성 (서버 측)
⚠️ AWS Lambda에서는
unstable_httpBatchStreamLink가 지원되지 않습니다(일반httpBatchLink처럼 동작함). 활성화해도 문제를 일으키지는 않지만 아무런 효과가 없습니다.
⚠️ Cloudflare Workers에서는 기능 플래그
streams_enable_constructors를 통해ReadableStreamAPI를 활성화해야 합니다.
참조
이 링크의 소스 코드는 GitHub에서 확인할 수 있습니다.