aboutsummaryrefslogtreecommitdiff
path: root/src/client/util/PingManager.ts
blob: e5e69c5acea949851a0d057bd310b2d338a828e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { action, makeObservable, observable, runInAction } from 'mobx';
import { Networking } from '../Network';
import { CurrentUserUtils } from './CurrentUserUtils';

export class PingManager {
    // create static instance and getter for global use
    // eslint-disable-next-line no-use-before-define
    @observable static _instance: PingManager;
    @observable IsBeating = true;
    static get Instance(): PingManager {
        return PingManager._instance;
    }

    // not used now, but may need to clear interval
    private _interval: NodeJS.Timeout | null = null;
    INTERVAL_SECONDS = 1;
    constructor() {
        makeObservable(this);
        PingManager._instance = this;
        this._interval = setInterval(this.sendPing, this.INTERVAL_SECONDS * 1000);
    }

    private setIsBeating = action((status: boolean) => {
        this.IsBeating = status;
        setTimeout(this.showAlert, 100);
    });

    showAlert = () => {
        alert(PingManager.Instance.IsBeating ? 'The server connection is active' : 'The server connection has been interrupted.NOTE: Any changes made will appear to persist but will be lost after a browser refreshes.');
    };
    sendPing = async (): Promise<void> => {
        try {
            const res = await Networking.PostToServer('/ping', { date: new Date() });
            runInAction(() => {
                CurrentUserUtils.ServerVersion = res.message;
            });
            !this.IsBeating && this.setIsBeating(true);
        } catch {
            if (this.IsBeating) {
                this.setIsBeating(false);
            }
        }
    };
}