Enlace de Lote HTTP
Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →
httpBatchLink es un enlace de terminación que agrupa un conjunto de operaciones individuales de tRPC en una única solicitud HTTP que se envía a un único procedimiento tRPC.
Uso
Puedes importar y agregar httpBatchLink al array links de esta manera:
client/index.tstsimport { createTRPCClient, httpBatchLink } from '@trpc/client';import type { AppRouter } from '../server';const client = createTRPCClient<AppRouter>({links: [httpBatchLink({url: 'http://localhost:3000',// transformer,}),],});
client/index.tstsimport { createTRPCClient, httpBatchLink } from '@trpc/client';import type { AppRouter } from '../server';const client = createTRPCClient<AppRouter>({links: [httpBatchLink({url: 'http://localhost:3000',// transformer,}),],});
Después, puedes aprovechar la agrupación colocando todos tus procedimientos en un Promise.all. El siguiente código producirá exactamente una solicitud HTTP y en el servidor exactamente una consulta a la base de datos:
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),]);
Opciones de httpBatchLink
La función httpBatchLink recibe un objeto de opciones que sigue la forma de HTTPBatchLinkOptions.
tsexport interface HTTPBatchLinkOptions extends HTTPLinkOptions {/*** 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 interface HTTPLinkOptions {url: string;/*** Add ponyfill for fetch*/fetch?: typeof fetch;/*** Add ponyfill for AbortController*/AbortController?: typeof AbortController | null;/*** Data transformer* @see https://trpc.io/docs/data-transformers**/transformer?: DataTransformerOptions;/*** Headers to be set on outgoing requests or a callback that of said headers* @see http://trpc.io/docs/header*/headers?:| HTTPHeaders| ((opts: { opList: Operation[] }) => HTTPHeaders | Promise<HTTPHeaders>);}
tsexport interface HTTPBatchLinkOptions extends HTTPLinkOptions {/*** 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 interface HTTPLinkOptions {url: string;/*** Add ponyfill for fetch*/fetch?: typeof fetch;/*** Add ponyfill for AbortController*/AbortController?: typeof AbortController | null;/*** Data transformer* @see https://trpc.io/docs/data-transformers**/transformer?: DataTransformerOptions;/*** Headers to be set on outgoing requests or a callback that of said headers* @see http://trpc.io/docs/header*/headers?:| HTTPHeaders| ((opts: { opList: Operation[] }) => HTTPHeaders | Promise<HTTPHeaders>);}
Configurar una longitud máxima de URL
Al enviar solicitudes por lotes, a veces la URL puede volverse demasiado larga causando errores HTTP como 413 Payload Too Large, 414 URI Too Long y 404 Not Found. La opción maxURLLength limitará la cantidad de solicitudes que pueden enviarse juntas en un lote.
Una alternativa para hacer esto es
client/index.tstsimport { createTRPCClient, httpBatchLink } from '@trpc/client';import type { AppRouter } from '../server';const client = 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';const client = 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',}),],});
Deshabilitar el procesamiento por lotes de solicitudes
1. Deshabilita batching en tu servidor:
server.tstsimport { createHTTPServer } from '@trpc/server/adapters/standalone';createHTTPServer({// [...]// 👇 disable batchingallowBatching: false,});
server.tstsimport { createHTTPServer } from '@trpc/server/adapters/standalone';createHTTPServer({// [...]// 👇 disable batchingallowBatching: false,});
o, si estás usando Next.js:
pages/api/trpc/[trpc].tstsexport default trpcNext.createNextApiHandler({// [...]// 👇 disable batchingallowBatching: false,});
pages/api/trpc/[trpc].tstsexport default trpcNext.createNextApiHandler({// [...]// 👇 disable batchingallowBatching: false,});
2. Reemplaza httpBatchLink con httpLink en tu cliente tRPC
client/index.tstsimport { createTRPCClient, httpLink } from '@trpc/client';import type { AppRouter } from '../server';const client = createTRPCClient<AppRouter>({links: [httpLink({url: 'http://localhost:3000',}),],});
client/index.tstsimport { createTRPCClient, httpLink } from '@trpc/client';import type { AppRouter } from '../server';const client = createTRPCClient<AppRouter>({links: [httpLink({url: 'http://localhost:3000',}),],});
o, si estás usando Next.js:
utils/trpc.tstsximport type { AppRouter } from '@/server/routers/app';import { httpLink } from '@trpc/client';import { createTRPCNext } from '@trpc/next';export const trpc = createTRPCNext<AppRouter>({config() {return {links: [httpLink({url: '/api/trpc',}),],};},});
utils/trpc.tstsximport type { AppRouter } from '@/server/routers/app';import { httpLink } from '@trpc/client';import { createTRPCNext } from '@trpc/next';export const trpc = createTRPCNext<AppRouter>({config() {return {links: [httpLink({url: '/api/trpc',}),],};},});