aboutsummaryrefslogtreecommitdiff
path: root/src/client/util/PingManager.ts
blob: 865f8bc02fd73c76f88f1d3519d63be8a138dfa4 (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
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
    @observable static _instance: PingManager;
    static get Instance(): PingManager {
        return PingManager._instance;
    }

    @observable IsBeating = true;
    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);
            }
        }
    };

    // 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);
    }
}