Skip to content
This repository has been archived by the owner on Jul 5, 2024. It is now read-only.

Commit

Permalink
fix: handle NodeJS.ReadableStream (#81)
Browse files Browse the repository at this point in the history
  • Loading branch information
KATT authored Oct 26, 2023
1 parent 44488a6 commit d190fa6
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
20 changes: 18 additions & 2 deletions src/async/iterableUtils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,24 @@
import { assert } from "../internals/assert.js";
import {
NodeJSReadableStreamEsque,
WebReadableStreamEsque,
} from "../internals/esque.js";

export async function* readableStreamToAsyncIterable<T>(
stream: ReadableStream<T>,
stream:
| NodeJSReadableStreamEsque
| ReadableStream<T>
| WebReadableStreamEsque,
): AsyncIterable<T> {
if (Symbol.asyncIterator in stream) {
// NodeJS.ReadableStream
for await (const chunk of stream) {
yield chunk as T;
}

return;
}

// Get a lock on the stream
const reader = stream.getReader();

Expand All @@ -18,7 +34,7 @@ export async function* readableStreamToAsyncIterable<T>(
}

// Else yield the chunk
yield result.value;
yield result.value as T;
}
} finally {
reader.releaseLock();
Expand Down
16 changes: 16 additions & 0 deletions src/internals/esque.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,19 @@
export interface TextDecoderEsque {
decode(chunk: Uint8Array): string;
}

/**
* A subset of the standard ReadableStream properties needed by tRPC internally.
* @see ReadableStream from lib.dom.d.ts
* @internal
*/
export interface WebReadableStreamEsque {
getReader: () => ReadableStreamDefaultReader<Uint8Array>;
}

/**
* @see NodeJS.ReadableStream from @types/node
*/
export interface NodeJSReadableStreamEsque {
[Symbol.asyncIterator]: () => AsyncIterableIterator<unknown>;
}

0 comments on commit d190fa6

Please sign in to comment.