aboutsummaryrefslogtreecommitdiffstats
path: root/web/src/js/connection.js
blob: 75c2cf258a12eb0e4f1ae993c9f0efc9a73698e3 (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
import {ConnectionActions, EventLogActions} from "./actions.js";
import {AppDispatcher} from "./dispatcher.js";
import * as websocketActions from "./ducks/websocket"

export default function Connection(url, dispatch) {
    if (url[0] === "/") {
        url = location.origin.replace("http", "ws") + url;
    }

    var ws = new WebSocket(url);
    ws.onopen = function () {
        dispatch(websocketActions.connected());
        ConnectionActions.open();
        //TODO: fetch stuff!
    };
    ws.onmessage = function (m) {
        var message = JSON.parse(m.data);
        AppDispatcher.dispatchServerAction(message);
        dispatch(message);
    };
    ws.onerror = function () {
        ConnectionActions.error();
        EventLogActions.add_event("WebSocket connection error.");
    };
    ws.onclose = function () {
        ConnectionActions.close();
        EventLogActions.add_event("WebSocket connection closed.");
        dispatch(websocketActions.disconnected());
    };
    return ws;
}