Enlace de transmisión por lotes HTTP
Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →
httpBatchStreamLink es un enlace terminal que agrupa un conjunto de operaciones individuales de tRPC en una única solicitud HTTP enviada a un único procedimiento tRPC (equivalente a httpBatchLink), pero no espera a que todas las respuestas del lote estén listas y transmite las respuestas tan pronto como hay datos disponibles.
Opciones
Las opciones son idénticas a httpBatchLink options, con la siguiente adición:
| Option | Type | Default | Description |
|---|---|---|---|
streamHeader | 'trpc-accept' | 'accept' | 'trpc-accept' | Which header to use to signal the server that the client wants a streaming response. 'accept' uses the standard Accept header instead of the custom trpc-accept header, which can avoid CORS preflight for cross-origin streaming queries since Accept is a CORS-safelisted header. |
Uso
Todo el uso y las opciones son idénticos a
httpBatchLink.
Si necesitas cambiar o establecer encabezados de respuesta (incluyendo cookies) desde tus procedimientos, ¡asegúrate de usar httpBatchLink en su lugar! Esto se debe a que httpBatchStreamLink no admite establecer encabezados una vez que la transmisión ha comenzado. Más información.
Puedes importar y agregar httpBatchStreamLink al array de links de esta manera:
client/index.tstsimport {createTRPCClient ,httpBatchStreamLink } from '@trpc/client';import type {AppRouter } from './server';constclient =createTRPCClient <AppRouter >({links : [httpBatchStreamLink ({url : 'http://localhost:3000',}),],});
client/index.tstsimport {createTRPCClient ,httpBatchStreamLink } from '@trpc/client';import type {AppRouter } from './server';constclient =createTRPCClient <AppRouter >({links : [httpBatchStreamLink ({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:
tsconstsomePosts = awaitPromise .all ([trpc .post .byId .query (1),trpc .post .byId .query (2),trpc .post .byId .query (3),]);
tsconstsomePosts = awaitPromise .all ([trpc .post .byId .query (1),trpc .post .byId .query (2),trpc .post .byId .query (3),]);
Modo de transmisión
Al agrupar solicitudes, el comportamiento normal de httpBatchLink es esperar a que todas las solicitudes finalicen antes de enviar la respuesta. Si deseas enviar respuestas tan pronto como estén disponibles, puedes usar httpBatchStreamLink en su lugar. Esto es útil para solicitudes de larga duración.
client/index.tstsimport {createTRPCClient ,httpBatchStreamLink } from '@trpc/client';import type {AppRouter } from './server';constclient =createTRPCClient <AppRouter >({links : [httpBatchStreamLink ({url : 'http://localhost:3000',}),],});
client/index.tstsimport {createTRPCClient ,httpBatchStreamLink } from '@trpc/client';import type {AppRouter } from './server';constclient =createTRPCClient <AppRouter >({links : [httpBatchStreamLink ({url : 'http://localhost:3000',}),],});
Comparado con un httpBatchLink regular, httpBatchStreamLink:
-
Hace que las solicitudes se envíen con un encabezado
trpc-accept: application/jsonl(oAccept: application/jsonlcuando se usastreamHeader: 'accept') -
Hace que la respuesta se envíe con
transfer-encoding: chunkedycontent-type: application/jsonl -
Elimina la clave
datadel objeto de argumentos pasado aresponseMeta(porque con una respuesta transmitida, los encabezados se envían antes de que los datos estén disponibles)
Generadores asíncronos y promesas diferidas
Puedes probar esto en la página de inicio de tRPC.io: https://trpc.io/?try=minimal#try-it-out
tsimport {createTRPCClien t,httpB atchStreamLink } from '@trpc/client';import type { AppRouter } from './server';const trpc = createTRPCClient<AppRouter>({links: [httpBatchStreamLink({ url:'http ://localh ost:3000',}),],});const iterable = await trpc.examples.iterable.query();for await (const value of iterable) {console.log('Iterable:', value);}
tsimport {createTRPCClien t,httpB atchStreamLink } from '@trpc/client';import type { AppRouter } from './server';const trpc = createTRPCClient<AppRouter>({links: [httpBatchStreamLink({ url:'http ://localh ost:3000',}),],});const iterable = await trpc.examples.iterable.query();for await (const value of iterable) {console.log('Iterable:', value);}
Compatibilidad (lado del cliente)
Navegadores
La compatibilidad con navegadores debe ser idéntica al soporte de fetch.
Node.js / Deno
Para entornos distintos a los navegadores, la implementación de fetch debe admitir transmisión, lo que significa que la respuesta obtenida mediante await fetch(...) debe tener una propiedad body de tipo ReadableStream<Uint8Array> | NodeJS.ReadableStream, lo que implica que:
-
response.body.getReaderes una función que devuelve un objetoReadableStreamDefaultReader<Uint8Array> -
o
response.bodyes unBufferde tipoUint8Array
Esto incluye soporte para undici, node-fetch, la implementación nativa de fetch en Node.js y la implementación de fetch de WebAPI (navegadores).
React Native
La recepción de la transmisión depende de las API TextDecoder y TextDecoderStream, que no están disponibles en React Native. Es importante notar que si tu polyfill de TextDecoderStream no incluye automáticamente ReadableStream y WritableStream, también será necesario aplicar polyfills a estos. Si aún deseas habilitar la transmisión, necesitas aplicar polyfills a estas APIs.
También necesitarás reemplazar la implementación de fetch predeterminada en las opciones de configuración de httpBatchStreamLink. En el siguiente ejemplo usaremos el paquete Expo fetch para la implementación de fetch.
tsimport { httpBatchStreamLink } from '@trpc/client';httpBatchStreamLink({fetch: (url, opts) =>fetch(url, {...opts,reactNative: { textStreaming: true },}),url: 'http://localhost:3000',});
tsimport { httpBatchStreamLink } from '@trpc/client';httpBatchStreamLink({fetch: (url, opts) =>fetch(url, {...opts,reactNative: { textStreaming: true },}),url: 'http://localhost:3000',});
Compatibilidad (lado del servidor)
httpBatchStreamLink solo es compatible con AWS Lambda cuando tu infraestructura está configurada para respuestas de transmisión. De lo contrario, este enlace se comportará como un httpBatchLink normal.
Necesitas habilitar la API ReadableStream mediante un indicador de función: streams_enable_constructors.
Referencia
Puedes consultar el código fuente de este enlace en GitHub.
Configurar una opción de ping para mantener la conexión activa
Al configurar tu raíz de configuración, puedes pasar una opción jsonl para configurar un ping que mantenga la conexión activa.
tsimport {initTRPC } from '@trpc/server';constt =initTRPC .create ({jsonl : {pingMs : 1000,},});
tsimport {initTRPC } from '@trpc/server';constt =initTRPC .create ({jsonl : {pingMs : 1000,},});