]> Untitled Git - lemmy-ui.git/blob - src/shared/services/WebSocketService.ts
Fixing nav-link
[lemmy-ui.git] / src / shared / services / WebSocketService.ts
1 import { PersonViewSafe, WebSocketJsonResponse } from "lemmy-js-client";
2 import {
3   default as ReconnectingWebSocket,
4   Options as WSOptions,
5 } from "reconnecting-websocket";
6 import { Observable } from "rxjs";
7 import { share } from "rxjs/operators";
8 import { wsUri } from "../env";
9 import { isBrowser } from "../utils";
10
11 export class WebSocketService {
12   private static _instance: WebSocketService;
13   private ws: ReconnectingWebSocket;
14   public wsOptions: WSOptions = {
15     connectionTimeout: 5000,
16     maxRetries: 10,
17   };
18   public subject: Observable<any>;
19
20   public admins: PersonViewSafe[];
21   public banned: PersonViewSafe[];
22
23   private constructor() {
24     this.ws = new ReconnectingWebSocket(wsUri, [], this.wsOptions);
25     let firstConnect = true;
26
27     this.subject = new Observable((obs: any) => {
28       this.ws.onmessage = e => {
29         obs.next(JSON.parse(e.data));
30       };
31       this.ws.onopen = () => {
32         console.log(`Connected to ${wsUri}`);
33
34         if (!firstConnect) {
35           let res: WebSocketJsonResponse<any> = {
36             reconnect: true,
37           };
38           obs.next(res);
39         }
40
41         firstConnect = false;
42       };
43     }).pipe(share());
44
45     if (isBrowser()) {
46       window.onunload = () => {
47         this.ws.close();
48
49         // Clears out scroll positions.
50         sessionStorage.clear();
51       };
52     }
53   }
54
55   public send(data: string) {
56     this.ws.send(data);
57   }
58
59   public closeEventListener(listener: (event: CloseEvent) => void) {
60     this.ws.addEventListener("close", listener);
61   }
62
63   public static get Instance() {
64     return this._instance || (this._instance = new this());
65   }
66 }