]> Untitled Git - lemmy-ui.git/blob - src/shared/services/WebSocketService.ts
Change from using Link to NavLink. resolve #269
[lemmy-ui.git] / src / shared / services / WebSocketService.ts
1 import { wsUri } from "../env";
2 import { PersonViewSafe, WebSocketJsonResponse } from "lemmy-js-client";
3 import { isBrowser } from "../utils";
4 import { Observable } from "rxjs";
5 import { share } from "rxjs/operators";
6 import {
7   Options as WSOptions,
8   default as ReconnectingWebSocket,
9 } from "reconnecting-websocket";
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.onbeforeunload = () => {
47         this.ws.close();
48       };
49     }
50   }
51
52   public send(data: string) {
53     this.ws.send(data);
54   }
55
56   public static get Instance() {
57     return this._instance || (this._instance = new this());
58   }
59 }