HTTP 批量链接
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
httpBatchLink 是一个终止链接,它可将多个独立的 tRPC 操作批处理成单个 HTTP 请求,并发送到单个 tRPC 过程。
用法
你可以按如下方式导入并将 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 可能因过长而触发 HTTP 错误,例如 413 Payload Too Large、414 URI Too Long 或 404 Not Found。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',}),],};},});