Website Summary Files Commits Branches @commit @diff @stats
path: root / scripts / services / socketService.js
blob: 4c328d7cab28aa2a52bae03ac78994951a0f6e24 (plain) (blame)
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
var app = app || {};

class SocketService {
    constructor() {
        this.connection = null;
        this.init();
    }

    async initConnection() {
        this.connection = await new signalR.HubConnectionBuilder()
            .withUrl("https://pusg-api.herokuapp.com/home")
            .build();
    }

    initReceivers() {
        this.connection.on('OnConnected', ([message]) => {
            console.log(message);
        });

        this.connection.on('ReceiveMessage', ([user, message]) => {
            const messageNode = app.htmlService
                .getElementFromTemplate('message', {
                    user: user,
                    message: message
                });

            app.htmlService.attachElement(app.htmlService.createElement(messageNode)
                , '.history-messages');
        });
    }

    init() {
        this.initConnection().then(() => {
            this.initReceivers();
            this.start();
        });
    }

    start() {
        const starting = async () => {
            try {
                await this.connection.start();
            } catch (e) {
                console.log(e);
            }
        };

        starting().then(() => {});
    }

    send(method, ...args) {
        this.connection.invoke(method, ...args);
    }
}

app.socketService = new SocketService();