HTTP 批处理流式链接
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
httpBatchStreamLink 是一个终止链接,它将多个独立的 tRPC 操作批处理成单个 HTTP 请求发送到单个 tRPC 过程(等同于 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完全相同。
如果需要在过程中修改/设置响应头(包括 cookies),请务必改用 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键(因为使用流式响应时,标头在数据可用前就已发送)
异步生成器与延迟 Promise
您可以在 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是Uint8Array类型的Buffer
这包括对 undici、node-fetch、原生 Node.js fetch 实现和 WebAPI fetch 实现(浏览器)的支持。
React Native
接收流式响应依赖 TextDecoder 和 TextDecoderStream API,这些 API 在 React Native 中不可用。需特别注意:若您的 TextDecoderStream polyfill 未自动 polyfill ReadableStream 和 WritableStream,则必须额外 polyfill 这些 API。若仍需启用流式传输,必须实现这些 polyfill。
您还需在 httpBatchStreamLink 配置选项中覆盖默认 fetch 实现。下例将使用 Expo fetch 包作为 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',});
兼容性(服务端)
仅当您的基础设施已配置流式响应支持时,才能在 AWS Lambda 上使用 httpBatchStreamLink。否则该链接的行为将与常规 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,},});