Skip to content

Commit

Permalink
Improve first argument's validation (#73)
Browse files Browse the repository at this point in the history
  • Loading branch information
ehmicky authored Aug 9, 2023
1 parent 3647016 commit b9bb7bb
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
6 changes: 4 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ export default async function getStream(stream, options) {
}

const getStreamContents = async (stream, {convertChunk, getContents}, {maxBuffer = Number.POSITIVE_INFINITY} = {}) => {
if (!stream) {
throw new Error('Expected a stream');
if (!isAsyncIterable(stream)) {
throw new Error('The first argument must be a Readable.');
}

let length = 0;
Expand All @@ -42,6 +42,8 @@ const getStreamContents = async (stream, {convertChunk, getContents}, {maxBuffer
}
};

const isAsyncIterable = stream => typeof stream === 'object' && stream !== null && typeof stream[Symbol.asyncIterator] === 'function';

const getBufferedData = (chunks, getContents, length) => {
try {
return getContents(chunks, length);
Expand Down
9 changes: 9 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,15 @@ test('handles streams with a single chunk larger than string max length', async
t.is(bufferedData, '');
});

const firstArgumentCheck = async (t, firstArgument) => {
await t.throwsAsync(getStream(firstArgument), {message: /first argument/});
};

test('Throws if the first argument is undefined', firstArgumentCheck, undefined);
test('Throws if the first argument is null', firstArgumentCheck, null);
test('Throws if the first argument is a string', firstArgumentCheck, '');
test('Throws if the first argument is an array', firstArgumentCheck, []);

test('native string', async t => {
const result = await text(compose(fixtureString));
t.is(result, fixtureString);
Expand Down

0 comments on commit b9bb7bb

Please sign in to comment.