Skip to content

Commit

Permalink
Provide exactly one handler for events and another for fatal errors (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
ptpaterson committed Mar 21, 2024
1 parent 7b6e3e7 commit 398c1f4
Showing 1 changed file with 11 additions and 17 deletions.
28 changes: 11 additions & 17 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -624,13 +624,6 @@ export type StreamEventHandler = (event: StreamEvent) => void;

export class StreamClient {
closed = false;
#callbacks: Record<StreamEventType, StreamEventHandler[]> = {
start: [],
add: [],
remove: [],
update: [],
error: [],
};
#query: () => Promise<StreamToken>;
#clientConfiguration: Record<string, any>;
#httpStreamClient: HTTPStreamClient;
Expand All @@ -650,12 +643,15 @@ export class StreamClient {
this.#httpStreamClient = httpStreamClient;
}

on(type: StreamEventType, callback: StreamEventHandler) {
this.#callbacks[type].push(callback);
return this;
}

start(onFatalError?: (error: Error) => void) {
start(
onEvent: StreamEventHandler,
onFatalError: (error: Error) => void
): StreamClient {
if (typeof onEvent !== "function") {
throw new TypeError(
`Expected a function as the 'onEvent' argument, but received ${typeof onEvent}. Please provide a valid function.`
);
}
if (onFatalError && typeof onFatalError !== "function") {
throw new TypeError(
`Expected a function as the 'onFatalError' argument, but received ${typeof onFatalError}. Please provide a valid function.`
Expand All @@ -664,10 +660,7 @@ export class StreamClient {
const run = async () => {
try {
for await (const event of this) {
const callbacks = this.#callbacks[event.type];
if (callbacks) {
this.#callbacks[event.type].forEach((callback) => callback(event));
}
onEvent(event);
}
} catch (error) {
if (onFatalError) {
Expand All @@ -676,6 +669,7 @@ export class StreamClient {
}
};
run();
return this;
}

async *[Symbol.asyncIterator](): AsyncGenerator<StreamEvent> {
Expand Down

0 comments on commit 398c1f4

Please sign in to comment.