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