Saltar al contenido principal
Versión: 9.x

Links y Agrupación de Solicitudes

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 →

Similar a los exchanges de urql o los links de Apollo. Los Links te permiten personalizar el flujo de datos entre el cliente tRPC y el servidor tRPC.

Agrupación de Solicitudes

La agrupación de solicitudes está activada automáticamente, lo que combina tus peticiones al servidor. Esto permite que el siguiente código produzca exactamente una solicitud HTTP y en el servidor exactamente una consulta a la base de datos:

ts
// below will be done in the same request when batching is enabled
const somePosts = await Promise.all([
client.query('post.byId', 1),
client.query('post.byId', 2),
client.query('post.byId', 3),
]);
ts
// below will be done in the same request when batching is enabled
const somePosts = await Promise.all([
client.query('post.byId', 1),
client.query('post.byId', 2),
client.query('post.byId', 3),
]);

Personalización del flujo de datos

Los siguientes ejemplos asumen que usas Next.js, pero puedes aplicar lo mismo si utilizas el cliente vanilla de tRPC

Establecer un tamaño máximo de lote

Esto limita la cantidad de solicitudes que pueden enviarse juntas en un lote (útil para evitar que la URL crezca demasiado y genere un error HTTP 413).

server.ts
ts
// 👇 import the httpBatchLink
import { httpBatchLink } from '@trpc/client/links/httpBatchLink';
import { withTRPC } from '@trpc/next';
import { AppType } from 'next/dist/shared/lib/utils';
import type { AppRouter } from 'pages/api/trpc/[trpc]';
const MyApp: AppType = ({ Component, pageProps }) => {
return <Component {...pageProps} />;
};
export default withTRPC<AppRouter>({
config() {
return {
links: [
httpBatchLink({
url: '/api/trpc',
maxBatchSize: 10, // a reasonable size
}),
],
};
},
})(MyApp);
server.ts
ts
// 👇 import the httpBatchLink
import { httpBatchLink } from '@trpc/client/links/httpBatchLink';
import { withTRPC } from '@trpc/next';
import { AppType } from 'next/dist/shared/lib/utils';
import type { AppRouter } from 'pages/api/trpc/[trpc]';
const MyApp: AppType = ({ Component, pageProps }) => {
return <Component {...pageProps} />;
};
export default withTRPC<AppRouter>({
config() {
return {
links: [
httpBatchLink({
url: '/api/trpc',
maxBatchSize: 10, // a reasonable size
}),
],
};
},
})(MyApp);

Deshabilitar la agrupación de solicitudes

1. Desactiva batching en tu servidor:

En tu [trpc].ts:

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

2. Usa un enlace sin agrupación en tu cliente tRPC

pages/_app.tsx
tsx
// 👇 import the httpLink
import { httpLink } from '@trpc/client/links/httpLink';
import { withTRPC } from '@trpc/next';
import { AppType } from 'next/dist/shared/lib/utils';
import type { AppRouter } from 'pages/api/trpc/[trpc]';
const MyApp: AppType = ({ Component, pageProps }) => {
return <Component {...pageProps} />;
};
export default withTRPC<AppRouter>({
config() {
return {
links: [
httpLink({
url: '/api/trpc',
}),
],
};
},
// ssr: false,
})(MyApp);
pages/_app.tsx
tsx
// 👇 import the httpLink
import { httpLink } from '@trpc/client/links/httpLink';
import { withTRPC } from '@trpc/next';
import { AppType } from 'next/dist/shared/lib/utils';
import type { AppRouter } from 'pages/api/trpc/[trpc]';
const MyApp: AppType = ({ Component, pageProps }) => {
return <Component {...pageProps} />;
};
export default withTRPC<AppRouter>({
config() {
return {
links: [
httpLink({
url: '/api/trpc',
}),
],
};
},
// ssr: false,
})(MyApp);

Deshabilitar agrupación para solicitudes específicas

1. Configura el cliente / _app.tsx
pages/_app.tsx
tsx
import { httpBatchLink } from '@trpc/client/links/httpBatchLink';
import { httpLink } from '@trpc/client/links/httpLink';
import { splitLink } from '@trpc/client/links/splitLink';
import { withTRPC } from '@trpc/next';
// [..]
export default withTRPC<AppRouter>({
config() {
const url = `http://localhost:3000`;
return {
links: [
splitLink({
condition(op) {
// check for context property `skipBatch`
return op.context.skipBatch === true;
},
// when condition is true, use normal request
true: httpLink({
url,
}),
// when condition is false, use batching
false: httpBatchLink({
url,
}),
}),
],
};
},
})(MyApp);
pages/_app.tsx
tsx
import { httpBatchLink } from '@trpc/client/links/httpBatchLink';
import { httpLink } from '@trpc/client/links/httpLink';
import { splitLink } from '@trpc/client/links/splitLink';
import { withTRPC } from '@trpc/next';
// [..]
export default withTRPC<AppRouter>({
config() {
const url = `http://localhost:3000`;
return {
links: [
splitLink({
condition(op) {
// check for context property `skipBatch`
return op.context.skipBatch === true;
},
// when condition is true, use normal request
true: httpLink({
url,
}),
// when condition is false, use batching
false: httpBatchLink({
url,
}),
}),
],
};
},
})(MyApp);
2. Realiza la solicitud sin agrupación
MyComponent.tsx
tsx
export function MyComponent() {
const postsQuery = trpc.useQuery(['posts'], {
context: {
skipBatch: true,
},
});
return (
<pre>{JSON.stringify(postsQuery.data ?? null, null, 4)}</pre>
)
})
MyComponent.tsx
tsx
export function MyComponent() {
const postsQuery = trpc.useQuery(['posts'], {
context: {
skipBatch: true,
},
});
return (
<pre>{JSON.stringify(postsQuery.data ?? null, null, 4)}</pre>
)
})

o:

client.ts
ts
const postResult = client.query('posts', null, {
context: {
skipBatch: true,
},
});
client.ts
ts
const postResult = client.query('posts', null, {
context: {
skipBatch: true,
},
});

Crear un enlace personalizado

pages/_app.tsx
tsx
import { TRPCLink } from '@trpc/client';
import type { AppRouter } from 'pages/api/trpc/[trpc]';
const customLink: TRPCLink<AppRouter> = (runtime) => {
// here we just got initialized in the app - this happens once per app
// useful for storing cache for instance
return ({ prev, next, op }) => {
// this is when passing the result to the next link
next(op, (result) => {
// this is when we've gotten result from the server
if (result instanceof Error) {
// maybe send to bugsnag?
}
prev(result);
});
};
};
export default withTRPC<AppRouter>({
config() {
return {
links: [
customLink,
// [..]
// ❗ Make sure to end with a `httpBatchLink` or `httpLink`
],
};
},
// ssr: false
})(MyApp);
pages/_app.tsx
tsx
import { TRPCLink } from '@trpc/client';
import type { AppRouter } from 'pages/api/trpc/[trpc]';
const customLink: TRPCLink<AppRouter> = (runtime) => {
// here we just got initialized in the app - this happens once per app
// useful for storing cache for instance
return ({ prev, next, op }) => {
// this is when passing the result to the next link
next(op, (result) => {
// this is when we've gotten result from the server
if (result instanceof Error) {
// maybe send to bugsnag?
}
prev(result);
});
};
};
export default withTRPC<AppRouter>({
config() {
return {
links: [
customLink,
// [..]
// ❗ Make sure to end with a `httpBatchLink` or `httpLink`
],
};
},
// ssr: false
})(MyApp);