ff-operation/src/stores/admin/operation/connection.ts

82 lines
2.6 KiB
TypeScript
Raw Normal View History

2025-02-21 11:55:49 +01:00
import { defineStore } from "pinia";
2025-02-26 16:26:43 +01:00
import { io, Socket } from "socket.io-client";
2025-02-21 11:55:49 +01:00
import { useNotificationStore } from "../../notification";
2025-02-25 18:35:17 +01:00
import { refreshToken, url } from "../../../serverCom";
2025-02-21 11:55:49 +01:00
export const useConnectionStore = defineStore("connection", {
state: () => {
return {
connection: undefined as undefined | Socket,
};
},
getters: {
connectionStatus: (state) => !!state.connection,
},
actions: {
connectClient(): void {
if (this.connectionStatus) return;
const notificationStore = useNotificationStore();
this.connection?.disconnect();
this.connection = io(url, {
reconnection: true,
2025-02-26 16:26:43 +01:00
reconnectionDelayMax: 1000,
reconnectionAttempts: 1,
2025-02-25 18:35:17 +01:00
auth: (cb) => {
cb({ token: localStorage.getItem("accessToken") });
2025-02-21 11:55:49 +01:00
},
});
this.connection.on("connect", () => {
2025-02-25 18:35:17 +01:00
notificationStore.push("Socket-Erfolg", `Verbindung aufgebaut`, "success");
2025-02-21 11:55:49 +01:00
});
2025-02-25 18:35:17 +01:00
this.connection.on("connect_error", (err) => {
this.handleError(err, true);
2025-02-21 11:55:49 +01:00
});
this.connection.on("disconnecting", () => {
this.connection?.disconnect();
});
this.connection.on("disconnect", () => {
this.$reset();
});
this.connection.on("warning", (msg: string) => {
2025-02-25 18:35:17 +01:00
notificationStore.push("Socket-Warnung", msg, "warning");
2025-02-21 11:55:49 +01:00
});
this.connection.on("error", (msg: string) => {
2025-02-25 18:35:17 +01:00
this.handleError({
name: "Error",
message: msg,
});
2025-02-21 11:55:49 +01:00
});
},
disconnectClient(): void {
this.connection?.disconnect();
},
2025-02-25 18:35:17 +01:00
handleError(err: Error, onConnect = false) {
const notificationStore = useNotificationStore();
if (err.message == "xhr poll error") {
notificationStore.push("Socket-Netzwerk-Fehler", "Reconnect Versuch in 10s", "error");
2025-02-26 16:26:43 +01:00
this.disconnectClient();
setTimeout(() => {
console.log("hi");
this.connectClient();
}, 10000);
2025-02-25 18:35:17 +01:00
} else if (err.message == "Token expired") {
notificationStore.push("Session", "Session wird verlängert", "info");
refreshToken()
.then(() => {
notificationStore.push("Session", "Session erfolgreich verlängert", "success");
this.connection?.disconnect().connect();
})
.catch(() => {
notificationStore.push("Session-Fehler", "Anmeldung wurde nicht verlängert", "error");
});
} else if (onConnect) {
notificationStore.push("Socket-Fehler", `Verbindung fehlgeschlagen`, "error");
} else {
notificationStore.push("Socket-Fehler", err.message, "error");
}
},
2025-02-21 11:55:49 +01:00
},
});