1
0
mirror of https://gitlab.nic.cz/turris/reforis/foris-js.git synced 2024-12-24 00:01:36 +01:00

WIP: Using socket.io for websocket handling

This commit is contained in:
Stepan Henek 2022-04-21 17:37:25 +02:00
parent f3a1090dbd
commit 1fae301499
No known key found for this signature in database
GPG Key ID: 08081019647EB8F2
3 changed files with 194 additions and 19330 deletions

19460
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -14,6 +14,7 @@
"license": "GPL-3.0",
"main": "./src/index.js",
"dependencies": {
"socket.io-client": "4.4.1",
"axios": "^0.21.1",
"immutability-helper": "3.0.1",
"moment": "^2.24.0",

View File

@ -7,49 +7,21 @@
/* eslint no-console: "off" */
const PROTOCOL = window.location.protocol === "http:" ? "ws" : "wss";
const URL = process.env.LIGHTTPD
? `${PROTOCOL}://${window.location.host}/${
process.env.WSPATH || "foris-ws"
}`
: `${PROTOCOL}://${window.location.hostname}:9081`;
const WAITING_FOR_CONNECTION_TIMEOUT = 500;
const { io } = require("socket.io-client");
export class WebSockets {
constructor() {
this.ws = new WebSocket(URL);
this.ws.onerror = (e) => {
console.error("WS: Error:", e);
};
this.ws.onmessage = (e) => {
console.debug(`WS: Received Message: ${e.data}`);
const data = JSON.parse(e.data);
this.dispatch(data);
};
this.ws.onopen = () => {
console.debug("WS: Connection open.");
};
this.ws.onclose = () => {
console.debug("WS: Connection closed.");
};
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 = {};
}
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] || [];
@ -57,13 +29,6 @@ export class WebSockets {
return this;
}
subscribe(module) {
this.waitForConnection(() => {
this.send("subscribe", module);
});
return this;
}
unbind(module, action, callback) {
const callbacks = this.callbacks[module][action];
@ -78,20 +43,14 @@ export class WebSockets {
if (Object.keys(this.callbacks[module]).length === 0) {
this.unsubscribe(module);
delete this.callbacks[module];
}
return this;
}
unsubscribe(module) {
this.waitForConnection(() => {
this.send("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);
@ -117,8 +76,4 @@ export class WebSockets {
chain.forEach((callback) => callback(json));
}
close() {
this.ws.close();
}
}