mirror of
https://gitlab.nic.cz/turris/reforis/foris-js.git
synced 2025-07-02 15:52:27 +02:00
80 lines
2.1 KiB
JavaScript
80 lines
2.1 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" */
|
|
|
|
const { io } = require("socket.io-client");
|
|
|
|
export class WebSockets {
|
|
constructor() {
|
|
this.socket = io("/notifications");
|
|
this.socket.on("disconnect", (reason) => {});
|
|
this.socket.on("notification", (notification) => {
|
|
// TODO call dispatch
|
|
});
|
|
this.socket.on("connect", (socket) => {});
|
|
|
|
// 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) {
|
|
this.unsubscribe(module);
|
|
delete this.callbacks[module];
|
|
}
|
|
|
|
return this;
|
|
}
|
|
|
|
send(action, params) {
|
|
// TODO may not be required
|
|
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 (error) {
|
|
if (error instanceof TypeError) {
|
|
console.warn(
|
|
`Callback for this message wasn't found:${error.data}`
|
|
);
|
|
} else throw error;
|
|
}
|
|
|
|
if (typeof chain === "undefined") return;
|
|
|
|
chain.forEach((callback) => callback(json));
|
|
}
|
|
}
|