mirror of
https://gitlab.nic.cz/turris/reforis/foris-js.git
synced 2025-04-20 08:16:38 +02:00
Socket.io wrapper is used to handle websockets now, this means that websocket logic had to be redone. Also it is necessary to set `REFORIS_PREFIX` env variable during the build process. To set the path of backend url. It was previously fixed to `/reforis`.
83 lines
2.3 KiB
JavaScript
83 lines
2.3 KiB
JavaScript
/*
|
|
* Copyright (C) 2020-2022 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.
|
|
*/
|
|
|
|
/* eslint no-console: "off" */
|
|
|
|
import { REFORIS_URL_PREFIX } from "../utils/forisUrls";
|
|
|
|
const { io } = require("socket.io-client");
|
|
|
|
export class WebSockets {
|
|
constructor() {
|
|
this.socket = io("/notifications", {
|
|
path: `${REFORIS_URL_PREFIX}/reforis-ws`,
|
|
});
|
|
this.connection = null;
|
|
this.socket.on("disconnect", (reason) => {
|
|
this.connection = null;
|
|
console.debug(`SocketIO disconnected (${reason})`);
|
|
});
|
|
this.socket.on("notification", (message) => {
|
|
console.debug("WS: Received Message:", message);
|
|
this.dispatch(message);
|
|
});
|
|
this.socket.on("connect", (connection) => {
|
|
this.connection = connection;
|
|
console.debug(`SocketIO connected.`);
|
|
});
|
|
|
|
// callbacks[module][action]
|
|
this.callbacks = {};
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
unbind(module, action, callback) {
|
|
const callbacks = this.callbacks[module][action];
|
|
|
|
const index = callbacks.indexOf(callback);
|
|
if (index !== -1) {
|
|
callbacks.splice(index, 1);
|
|
}
|
|
|
|
if (callbacks.length === 0) {
|
|
delete this.callbacks[module][action];
|
|
}
|
|
|
|
if (Object.keys(this.callbacks[module]).length === 0) {
|
|
delete this.callbacks[module];
|
|
}
|
|
|
|
return this;
|
|
}
|
|
|
|
dispatch(json) {
|
|
if (!json.module) return;
|
|
|
|
let chain;
|
|
try {
|
|
chain = this.callbacks[json.module][json.action];
|
|
} catch (error) {
|
|
if (error instanceof TypeError) {
|
|
console.debug(
|
|
`Callbacks for this module wasn't found: ${json.module}`
|
|
);
|
|
} else throw error;
|
|
}
|
|
|
|
if (typeof chain === "undefined") return;
|
|
|
|
console.debug("Handling WS message", json);
|
|
chain.forEach((callback) => callback(json));
|
|
}
|
|
}
|