Skip to content

Commit 941473f

Browse files
committed
getStreamIterator now throws TypeError for unsupported sources.
1 parent d97a405 commit 941473f

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

src/util/getStreamIterator.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,14 @@ test("Reads from the stream using fallback", async t => {
4949

5050
t.is(actual, expected)
5151
})
52+
53+
test("Throws TypeError for unsupported data sources", t => {
54+
// @ts-expect-error
55+
const trap = () => getStreamIterator({})
56+
57+
t.throws(trap, {
58+
instanceOf: TypeError,
59+
message: "Unsupported data source: Expected either "
60+
+ "ReadableStream or async iterable."
61+
})
62+
})

src/util/getStreamIterator.ts

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,17 @@ async function* readStream(
3737
*/
3838
export const getStreamIterator = (
3939
source: ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>
40-
): AsyncIterable<Uint8Array> => (
41-
isAsyncIterable(source) ? source : readStream(source)
42-
)
40+
): AsyncIterable<Uint8Array> => {
41+
if (isAsyncIterable(source)) {
42+
return source
43+
}
44+
45+
if (isFunction(source.getReader)) {
46+
return readStream(source)
47+
}
48+
49+
// Throw an error otherwise (for example, in case if encountered Node.js Readable stream without Symbol.asyncIterator method)
50+
throw new TypeError(
51+
"Unsupported data source: Expected either ReadableStream or async iterable."
52+
)
53+
}

0 commit comments

Comments
 (0)