Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide exactly one handler for events and another for fatal errors #234

Merged
merged 2 commits into from
Mar 8, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading