Länkar & Begärandebatchning
Denna sida har översatts av PageTurner AI (beta). Inte officiellt godkänd av projektet. Hittade du ett fel? Rapportera problem →
Påminner om urql:s exchanges eller Apollos links. Med länkar kan du anpassa dataflödet mellan tRPC-klienten och tRPC-servern.
Begärandebatchning
Begärandebatchning är automatiskt aktiverat, vilket samlar dina förfrågningar till servern. Detta kan göra att koden nedan resulterar i exakt ett HTTP-anrop och på servern exakt en databasfråga:
ts// below will be done in the same request when batching is enabledconst 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 enabledconst somePosts = await Promise.all([client.query('post.byId', 1),client.query('post.byId', 2),client.query('post.byId', 3),]);
Anpassa dataflöde
Exemplen nedan förutsätter att du använder Next.js, men samma tillvägagångssätt kan användas om du använder den vanilla tRPC-klienten
Ställa in maximal batchstorlek
Detta begränsar antalet förfrågningar som kan skickas tillsammans i en batch (användbart för att förhindra att URL:en blir för lång och leder till HTTP-fel 413).
server.tsts// 👇 import the httpBatchLinkimport { 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.tsts// 👇 import the httpBatchLinkimport { 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);
Inaktivera begärandebatchning
1. Inaktivera batching på din server:
I din [trpc].ts:
pages/api/trpc/[trpc].tstsexport default trpcNext.createNextApiHandler({// [...]// 👇 disable batchingbatching: {enabled: false,},});
pages/api/trpc/[trpc].tstsexport default trpcNext.createNextApiHandler({// [...]// 👇 disable batchingbatching: {enabled: false,},});
2. Använd en batchfri länk i din tRPC-klient
pages/_app.tsxtsx// 👇 import the httpLinkimport { 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.tsxtsx// 👇 import the httpLinkimport { 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);
Använda en splitLink för att kontrollera förfrågningsflöde
Inaktivera batchning för vissa förfrågningar
1. Konfigurera klienten / _app.tsx
pages/_app.tsxtsximport { 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 requesttrue: httpLink({url,}),// when condition is false, use batchingfalse: httpBatchLink({url,}),}),],};},})(MyApp);
pages/_app.tsxtsximport { 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 requesttrue: httpLink({url,}),// when condition is false, use batchingfalse: httpBatchLink({url,}),}),],};},})(MyApp);
2. Utför förfrågan utan batchning
MyComponent.tsxtsxexport function MyComponent() {const postsQuery = trpc.useQuery(['posts'], {context: {skipBatch: true,},});return (<pre>{JSON.stringify(postsQuery.data ?? null, null, 4)}</pre>)})
MyComponent.tsxtsxexport function MyComponent() {const postsQuery = trpc.useQuery(['posts'], {context: {skipBatch: true,},});return (<pre>{JSON.stringify(postsQuery.data ?? null, null, 4)}</pre>)})
eller:
client.tstsconst postResult = client.query('posts', null, {context: {skipBatch: true,},});
client.tstsconst postResult = client.query('posts', null, {context: {skipBatch: true,},});
Skapa en anpassad länk
pages/_app.tsxtsximport { 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 instancereturn ({ prev, next, op }) => {// this is when passing the result to the next linknext(op, (result) => {// this is when we've gotten result from the serverif (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.tsxtsximport { 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 instancereturn ({ prev, next, op }) => {// this is when passing the result to the next linknext(op, (result) => {// this is when we've gotten result from the serverif (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);