60 lines
2.1 KiB
JavaScript
60 lines
2.1 KiB
JavaScript
class Subscription {
|
|
constructor(options) {
|
|
var _a;
|
|
this.keepAliveLastReceivedAt = Date.now();
|
|
this.options = options;
|
|
const url = new URL(options.url);
|
|
const searchParams = new URLSearchParams(Object.entries(options.searchParams || {}).reduce((accumulator, [key, value]) => value === undefined
|
|
? accumulator
|
|
: ((accumulator[key] = value), accumulator), {}));
|
|
url.search = searchParams.toString();
|
|
this.url = url.toString();
|
|
this.eventSource = this.connect();
|
|
const keepAliveIntervalMs = (_a = this.options.keepAlive) === null || _a === void 0 ? void 0 : _a.intervalMs;
|
|
if (keepAliveIntervalMs) {
|
|
this.keepAliveTimer = setInterval(() => {
|
|
if (Date.now() - this.keepAliveLastReceivedAt > keepAliveIntervalMs) {
|
|
this.eventSource = this.connect();
|
|
}
|
|
}, 1000);
|
|
}
|
|
}
|
|
connect() {
|
|
var _a;
|
|
if (this.eventSource) {
|
|
this.eventSource.close();
|
|
}
|
|
const eventSource = new EventSource(this.url, {
|
|
...(this.options.eventSourceOptions || {}),
|
|
});
|
|
eventSource.addEventListener("message", (event) => {
|
|
if (this.options.onNext) {
|
|
this.options.onNext(event.data);
|
|
}
|
|
});
|
|
eventSource.addEventListener("error", () => {
|
|
if (this.options.onError) {
|
|
this.options.onError(new Error("Event source error."));
|
|
}
|
|
});
|
|
eventSource.addEventListener(((_a = this.options.keepAlive) === null || _a === void 0 ? void 0 : _a.eventType) || "keepAlive", () => {
|
|
this.keepAliveLastReceivedAt = Date.now();
|
|
});
|
|
return eventSource;
|
|
}
|
|
get closed() {
|
|
return false;
|
|
}
|
|
unsubscribe() {
|
|
if (this.keepAliveTimer !== "undefined") {
|
|
clearInterval(this.keepAliveTimer);
|
|
}
|
|
this.eventSource.close();
|
|
if (this.options.onComplete) {
|
|
this.options.onComplete();
|
|
}
|
|
}
|
|
}
|
|
|
|
export { Subscription };
|