ai
Version:
AI SDK by Vercel - build apps like ChatGPT, Claude, Gemini, and more with a single interface for any model using the Vercel AI Gateway or go direct to OpenAI, Anthropic, Google, or any other model provider.
45 lines (42 loc) • 1.24 kB
text/typescript
/**
* Consumes a ReadableStream until it's fully read.
*
* This function reads the stream chunk by chunk until the stream is exhausted.
* It doesn't process or return the data from the stream; it simply ensures
* that the entire stream is read.
*
* @param options - The options for consuming the stream.
* @param options.stream - The ReadableStream to be consumed.
* @param options.onError - Optional callback to handle errors that occur during consumption.
* @returns A promise that resolves when the stream is fully consumed.
*/
export async function consumeStream({
stream,
onError,
abortSignal,
}: {
stream: ReadableStream;
onError?: (error: unknown) => void;
abortSignal?: AbortSignal;
}): Promise<void> {
const reader = stream.getReader();
const cancelOnAbort = () => {
reader.cancel().catch(() => {});
};
if (abortSignal?.aborted) {
cancelOnAbort();
} else {
abortSignal?.addEventListener('abort', cancelOnAbort, { once: true });
}
try {
while (true) {
const { done } = await reader.read();
if (done) break;
}
} catch (error) {
onError?.(error);
} finally {
abortSignal?.removeEventListener('abort', cancelOnAbort);
reader.releaseLock();
}
}