mirror of
https://gitlab.com/openlp/web-remote.git
synced 2024-12-22 19:32:49 +00:00
36 lines
904 B
TypeScript
36 lines
904 B
TypeScript
import { Observable } from 'rxjs';
|
|
|
|
export function createWebSocket<T>(
|
|
host: string,
|
|
wsPort: number,
|
|
deserialize: (input: string) => T,
|
|
endpoint = ''
|
|
): Observable<T> {
|
|
return new Observable((observer) => {
|
|
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
const ws = new WebSocket(`${protocol}//${host}:${wsPort}/${endpoint}`);
|
|
ws.onmessage = (e) => {
|
|
const reader = new FileReader();
|
|
reader.onload = () => {
|
|
const data = deserialize(JSON.parse(reader.result as string));
|
|
observer.next(data);
|
|
};
|
|
reader.readAsText(e.data);
|
|
};
|
|
ws.onerror = () => {
|
|
observer.error();
|
|
};
|
|
ws.onclose = () => {
|
|
observer.complete();
|
|
};
|
|
|
|
return () => {
|
|
// Removing listeners to avoid loop
|
|
ws.onmessage = null;
|
|
ws.onclose = null;
|
|
ws.onerror = null;
|
|
ws.close();
|
|
};
|
|
});
|
|
}
|