Aller au contenu principal
Version : 11.x

Lien HTTP par lot

Traduction Bêta Non Officielle

Cette page a été traduite par PageTurner AI (bêta). Non approuvée officiellement par le projet. Vous avez trouvé une erreur ? Signaler un problème →

httpBatchLink est un lien terminal qui regroupe un ensemble d'opérations tRPC individuelles en une seule requête HTTP envoyée vers une procédure tRPC unique.

Utilisation

Vous pouvez importer et ajouter le httpBatchLink au tableau links comme ceci :

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

Ensuite, vous pouvez exploiter le regroupement en plaçant toutes vos procédures dans un Promise.all. Le code ci-dessous générera exactement une requête HTTP et sur le serveur exactement une requête de base de données :

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

Options de httpBatchLink

La fonction httpBatchLink prend un objet d'options correspondant au type 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;
/**
* 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>);
}
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;
/**
* 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>);
}

Définir une longueur maximale d'URL

Lors de l'envoi de requêtes groupées, l'URL peut parfois devenir trop longue, provoquant des erreurs HTTP comme 413 Payload Too Large, 414 URI Too Long ou 404 Not Found. L'option maxURLLength limite le nombre de requêtes pouvant être envoyées ensemble dans un lot.

Une autre approche consiste à

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

Désactiver le regroupement de requêtes

1. Désactivez batching sur votre serveur :

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

ou, si vous utilisez Next.js :

pages/api/trpc/[trpc].ts
ts
export default trpcNext.createNextApiHandler({
// [...]
// 👇 disable batching
allowBatching: false,
});
pages/api/trpc/[trpc].ts
ts
export default trpcNext.createNextApiHandler({
// [...]
// 👇 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',
}),
],
});

ou, si vous utilisez 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',
}),
],
};
},
});