Skip to content

Commit

Permalink
fix: throw helpful error if passing function to createParser()
Browse files Browse the repository at this point in the history
  • Loading branch information
rexxars committed Nov 4, 2024
1 parent 07d564b commit 4cd3a44
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ function noop(_arg: unknown) {
* @public
*/
export function createParser(callbacks: ParserCallbacks): EventSourceParser {
if (typeof callbacks === 'function') {
throw new TypeError(
'`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?',
)
}

const {onEvent = noop, onError = noop, onRetry = noop, onComment} = callbacks

let incompleteLine = ''
Expand Down
9 changes: 9 additions & 0 deletions test/parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -417,3 +417,12 @@ test('calls onError when the stream is invalid (no field separator)', async () =
line: 'Well, this is not what I expected',
})
})

test('passing a function to `createParser` will throw with helpful error', () => {
expect(() => {
// @ts-expect-error Should not allow a function, typing-wise
createParser(() => null)
}).toThrowError(
'`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?',
)
})

0 comments on commit 4cd3a44

Please sign in to comment.