Saltar al contenido principal
Versión: 10.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 { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from '../server';
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: 'http://localhost:3000',
}),
],
});
client/index.ts
ts
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from '../server';
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: 'http://localhost:3000',
}),
],
});

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),
]);

La función httpBatchLink recibe un objeto de opciones que sigue la forma de HTTPBatchLinkOptions.

ts
export interface HTTPBatchLinkOptions extends HTTPLinkOptions {
maxURLLength?: number;
}
export interface HTTPLinkOptions {
url: string;
/**
* Add ponyfill for fetch
*/
fetch?: typeof fetch;
/**
* Add ponyfill for AbortController
*/
AbortController?: typeof AbortController | null;
/**
* Headers to be set on outgoing requests or a callback that of said headers
* @see http://trpc.io/docs/v10/header
*/
headers?:
| HTTPHeaders
| ((opts: { opList: Operation[] }) => HTTPHeaders | Promise<HTTPHeaders>);
}
ts
export interface HTTPBatchLinkOptions extends HTTPLinkOptions {
maxURLLength?: number;
}
export interface HTTPLinkOptions {
url: string;
/**
* Add ponyfill for fetch
*/
fetch?: typeof fetch;
/**
* Add ponyfill for AbortController
*/
AbortController?: typeof AbortController | null;
/**
* Headers to be set on outgoing requests or a callback that of said headers
* @see http://trpc.io/docs/v10/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.

client/index.ts
ts
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from '../server';
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: 'http://localhost:3000',
maxURLLength: 2083, // a suitable size
}),
],
});
client/index.ts
ts
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from '../server';
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: 'http://localhost:3000',
maxURLLength: 2083, // a suitable size
}),
],
});

Deshabilitar el procesamiento por lotes de solicitudes

1. Deshabilita batching en tu servidor:

server.ts
ts
import { createHTTPServer } from '@trpc/server/adapters/standalone';
createHTTPServer({
// [...]
// 👇 disable batching
batching: {
enabled: false,
},
});
server.ts
ts
import { createHTTPServer } from '@trpc/server/adapters/standalone';
createHTTPServer({
// [...]
// 👇 disable batching
batching: {
enabled: false,
},
});

o, si estás usando Next.js:

pages/api/trpc/[trpc].ts
ts
export default trpcNext.createNextApiHandler({
// [...]
// 👇 disable batching
batching: {
enabled: false,
},
});
pages/api/trpc/[trpc].ts
ts
export default trpcNext.createNextApiHandler({
// [...]
// 👇 disable batching
batching: {
enabled: false,
},
});
client/index.ts
ts
import { createTRPCProxyClient, httpLink } from '@trpc/client';
import type { AppRouter } from '../server';
const client = createTRPCProxyClient<AppRouter>({
links: [
httpLink({
url: 'http://localhost:3000',
}),
],
});
client/index.ts
ts
import { createTRPCProxyClient, httpLink } from '@trpc/client';
import type { AppRouter } from '../server';
const client = createTRPCProxyClient<AppRouter>({
links: [
httpLink({
url: 'http://localhost:3000',
}),
],
});

o, si estás usando Next.js:

utils/trpc.ts
tsx
import 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.ts
tsx
import 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',
}),
],
};
},
});

Referencia

Puedes consultar el código fuente de este enlace en GitHub.