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

Check for a global EventSource before deciding what to use. #389

Merged
merged 2 commits into from
Jul 26, 2019
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
53 changes: 30 additions & 23 deletions src/call_builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,15 @@ export interface EventSourceOptions<T> {
}

let EventSource: Constructable<EventSource>;
const anyGlobal = global as any;

if (isNode) {
if (anyGlobal.EventSource) {
EventSource = anyGlobal.EventSource;
} else if (isNode) {
/* tslint:disable-next-line:no-var-requires */
EventSource = require("eventsource");
} else {
/* tslint:disable-next-line:variable-name */
EventSource = (global as any).window.EventSource;
EventSource = anyGlobal.window.EventSource;
}

/**
Expand Down Expand Up @@ -123,33 +125,38 @@ export class CallBuilder<

createTimeout();

es.onmessage = (message) => {
const result = message.data
? this._parseRecord(JSON.parse(message.data))
: message;
if (result.paging_token) {
this.url.setQuery("cursor", result.paging_token);
}
clearTimeout(timeout);
createTimeout();
if (typeof options.onmessage !== "undefined") {
options.onmessage(result);
}
};

es.onerror = (error) => {
if (options.onerror && error instanceof MessageEvent) {
options.onerror(error);
}
};
if (es) {
es.onmessage = (message) => {
const result = message.data
? this._parseRecord(JSON.parse(message.data))
: message;
if (result.paging_token) {
this.url.setQuery("cursor", result.paging_token);
}
clearTimeout(timeout);
createTimeout();
if (typeof options.onmessage !== "undefined") {
options.onmessage(result);
}
};

es.onerror = (error) => {
if (options.onerror && error instanceof MessageEvent) {
options.onerror(error);
}
};
}

return es;
};

createEventSource();
return function close() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I noticed before that this function keeps trying to write to es even if the assignment fails. I feel like it should return in the catch rather than continuing with the function. Can you make that fix too?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Definitely! :)

clearTimeout(timeout);
es.close();

if (es) {
es.close();
}
};
}

Expand Down