1
0
mirror of https://gitlab.nic.cz/turris/reforis/foris-js.git synced 2024-12-28 00:41:35 +01:00
foris-js/src/webSockets/WebSockets.js

100 lines
2.7 KiB
JavaScript
Raw Normal View History

2019-08-23 15:20:22 +02:00
/*
* Copyright (C) 2019 CZ.NIC z.s.p.o. (http://www.nic.cz/)
*
* This is free software, licensed under the GNU General Public License v3.
* See /LICENSE for more information.
*/
2019-08-27 16:09:18 +02:00
/* eslint no-console: "off" */
import { ForisURLs } from "forisUrls";
2019-08-23 15:20:22 +02:00
const PROTOCOL = window.location.protocol === "http:" ? "ws" : "wss";
const URL = process.env.LIGHTTPD
? `${PROTOCOL}://${window.location.hostname}/foris-ws`
: `${PROTOCOL}://${window.location.hostname}:${9081}`;
const WAITING_FOR_CONNECTION_TIMEOUT = 500;
2019-08-27 16:09:18 +02:00
export default class WebSockets {
2019-08-23 15:20:22 +02:00
constructor() {
this.ws = new WebSocket(URL);
this.ws.onerror = (e) => {
2019-08-27 16:09:18 +02:00
if (window.location.pathname !== ForisURLs.login) {
2019-08-23 15:20:22 +02:00
console.error("WS: Error observed, you aren't logged probably.");
2019-08-27 16:09:18 +02:00
window.location.replace(ForisURLs.login);
2019-08-23 15:20:22 +02:00
}
console.log(`WS: Error: ${e}`);
};
this.ws.onmessage = (e) => {
console.log(`WS: Received Message: ${e.data}`);
const data = JSON.parse(e.data);
this.dispatch(data);
};
this.ws.onopen = () => {
console.log("WS: Connection open.");
};
this.ws.onclose = () => {
console.log("WS: Connection closed.");
};
// callbacks[module][action]
this.callbacks = {};
}
waitForConnection(callback) {
if (this.ws.readyState === 1) {
callback();
} else {
const that = this;
setTimeout(() => {
that.waitForConnection(callback);
}, WAITING_FOR_CONNECTION_TIMEOUT);
}
}
bind(module, action, callback) {
this.callbacks[module] = this.callbacks[module] || {};
this.callbacks[module][action] = this.callbacks[module][action] || [];
this.callbacks[module][action].push(callback);
return this;
}
subscribe(params) {
this.waitForConnection(() => {
this.send("subscribe", params);
});
return this;
}
send(action, params) {
const payload = JSON.stringify({ action, params });
this.waitForConnection(() => {
this.ws.send(payload);
});
return this;
}
dispatch(json) {
if (!json.module) return;
let chain;
try {
chain = this.callbacks[json.module][json.action];
} catch (e) {
if (e instanceof TypeError) {
console.log(`Callback for this message wasn't found:${e.data}`);
} else throw e;
}
if (typeof chain === "undefined") return;
for (let i = 0; i < chain.length; i++) chain[i](json);
}
close() {
this.ws.close();
}
}