Saltar al contenido principal
Versión: 11.x

Enlace de Lote HTTP

Traducción Beta No Oficial

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.ts
ts
import { createTRPCClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from './server';
 
const client = createTRPCClient<AppRouter>({
links: [
httpBatchLink({
url: 'http://localhost:3000',
// transformer,
}),
],
});
client/index.ts
ts
import { 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:

ts
const somePosts = await Promise.all([
trpc.post.byId.query(1),
trpc.post.byId.query(2),
trpc.post.byId.query(3),
]);
ts
const 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.

ts
export 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 | URL;
/**
* Add ponyfill for fetch
*/
fetch?: typeof fetch;
/**
* 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>);
}
ts
export 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 | URL;
/**
* Add ponyfill for fetch
*/
fetch?: typeof fetch;
/**
* 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>);
}

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.

client/index.ts
ts
import { 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.ts
ts
import { 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',
}),
],
});

Limitar el tamaño del lote

1. Establece un tamaño máximo de lote en tu servidor:

maxBatchSize limita cuántas operaciones pueden enviarse en una única solicitud por lotes. Las solicitudes que excedan este límite serán rechazadas con un error 400 Bad Request. Esto puede pasarse a cualquier adaptador de tRPC.

server.ts
ts
import { createHTTPServer } from '@trpc/server/adapters/standalone';
createHTTPServer({
maxBatchSize: 10,
});
server.ts
ts
import { createHTTPServer } from '@trpc/server/adapters/standalone';
createHTTPServer({
maxBatchSize: 10,
});

o por ejemplo si usas Next.js:

pages/api/trpc/[trpc].ts
ts
export default trpcNext.createNextApiHandler({
maxBatchSize: 10,
});
pages/api/trpc/[trpc].ts
ts
export default trpcNext.createNextApiHandler({
maxBatchSize: 10,
});

2. Establece un límite equivalente en el cliente:

Usa la opción maxItems en tu enlace de lote para asegurar que el cliente no exceda el límite del servidor. Esto divide automáticamente lotes grandes en múltiples solicitudes HTTP.

client/index.ts
ts
import { 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 maxBatchSize
maxItems: 10,
}),
],
});
client/index.ts
ts
import { 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 maxBatchSize
maxItems: 10,
}),
],
});

Deshabilitar el procesamiento por lotes de solicitudes

1. Deshabilita batching en tu servidor:

server.ts
ts
import { createHTTPServer } from '@trpc/server/adapters/standalone';
import { appRouter } from './router';
 
createHTTPServer({
router: appRouter,
// 👇 disable batching
allowBatching: false,
});
server.ts
ts
import { createHTTPServer } from '@trpc/server/adapters/standalone';
import { appRouter } from './router';
 
createHTTPServer({
router: appRouter,
// 👇 disable batching
allowBatching: false,
});

o, si estás usando Next.js:

pages/api/trpc/[trpc].ts
ts
import { createNextApiHandler } from '@trpc/server/adapters/next';
import { appRouter } from '../../../router';
 
export default createNextApiHandler({
router: appRouter,
// 👇 disable batching
allowBatching: false,
});
pages/api/trpc/[trpc].ts
ts
import { createNextApiHandler } from '@trpc/server/adapters/next';
import { appRouter } from '../../../router';
 
export default createNextApiHandler({
router: appRouter,
// 👇 disable batching
allowBatching: false,
});
client/index.ts
ts
import { createTRPCClient, httpLink } from '@trpc/client';
import type { AppRouter } from './server';
 
const client = createTRPCClient<AppRouter>({
links: [
httpLink({
url: 'http://localhost:3000',
}),
],
});
client/index.ts
ts
import { 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.ts
tsx
import type { AppRouter } from '../server';
import { httpLink } from '@trpc/client';
import { createTRPCNext } from '@trpc/next';
 
export const trpc = createTRPCNext<AppRouter>({
config() {
return {
links: [
httpLink({
url: '/api/trpc',
}),
],
};
},
});
utils/trpc.ts
tsx
import type { AppRouter } from '../server';
import { httpLink } from '@trpc/client';
import { createTRPCNext } from '@trpc/next';
 
export const trpc = createTRPCNext<AppRouter>({
config() {
return {
links: [
httpLink({
url: '/api/trpc',
}),
],
};
},
});