Use browser build in EventSource for apiClient subscriptions

This commit is contained in:
Sebastian Sdorra
2020-03-20 11:15:35 +01:00
parent f8f5aa2ebd
commit 9ff5b26982
4 changed files with 13 additions and 11 deletions

View File

@@ -1,6 +1,4 @@
import { contextPath } from "./urls";
// @ts-ignore we have not types for event-source-polyfill
import { EventSourcePolyfill } from "event-source-polyfill";
import { createBackendError, ForbiddenError, isBackendError, UnauthorizedError, BackendErrorContent } from "./errors";
type SubscriptionEvent = {
@@ -124,6 +122,10 @@ export function createUrl(url: string) {
return `${contextPath}/api/v2${urlWithStartingSlash}`;
}
export function createUrlWithIdentifiers(url: string): string {
return createUrl(url) + "?X-SCM-Client=WUI&X-SCM-Session-ID=" + sessionId;
}
class ApiClient {
get(url: string): Promise<Response> {
return fetch(createUrl(url), applyFetchOptions({})).then(handleFailure);
@@ -218,9 +220,8 @@ class ApiClient {
}
subscribe(url: string, argument: SubscriptionArgument): Cancel {
const es = new EventSourcePolyfill(createUrl(url), {
withCredentials: true,
headers: createRequestHeaders()
const es = new EventSource(createUrlWithIdentifiers(url), {
withCredentials: true
});
let listeners: MessageListeners;
@@ -228,9 +229,11 @@ class ApiClient {
if ("onMessage" in argument) {
listeners = (argument as SubscriptionContext).onMessage;
if (argument.onError) {
// @ts-ignore typing of EventSource is weird
es.onerror = argument.onError;
}
if (argument.onOpen) {
// @ts-ignore typing of EventSource is weird
es.onopen = argument.onOpen;
}
} else {
@@ -238,6 +241,7 @@ class ApiClient {
}
for (const type in listeners) {
// @ts-ignore typing of EventSource is weird
es.addEventListener(type, listeners[type]);
}