import { defineStore } from "pinia"; import { io, type Socket } from "socket.io-client"; import { useNotificationStore } from "../../notification"; import { refreshToken, url } from "../../../serverCom"; 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, reconnectionDelayMax: 10000, auth: (cb) => { cb({ token: localStorage.getItem("accessToken") }); }, }); this.connection.on("connect", () => { notificationStore.push("Socket-Erfolg", `Verbindung aufgebaut`, "success"); }); this.connection.on("connect_error", (err) => { this.handleError(err, true); }); this.connection.on("disconnecting", () => { this.connection?.disconnect(); }); this.connection.on("disconnect", () => { this.$reset(); }); this.connection.on("warning", (msg: string) => { notificationStore.push("Socket-Warnung", msg, "warning"); }); this.connection.on("error", (msg: string) => { this.handleError({ name: "Error", message: msg, }); }); this.connection.on("reconnect", (attemptNumber) => { notificationStore.push("Socket-Reconnect", `Reconnect erfolgreich`, "success"); }); this.connection.on("reconnect_attempt", (attemptNumber) => { notificationStore.push("Socket-Reconnect-Versuch", `Reconnect-Versuch Nr.${attemptNumber}`, "info"); }); this.connection.on("reconnect_error", (error) => { notificationStore.push("Socket-Warnung", "Reconnect fehlgeschlagen", "warning"); }); this.connection.on("reconnect_failed", () => { notificationStore.push("Socket-Fehler", "Reconnect-Versuche erfolglos beendet", "error"); }); }, disconnectClient(): void { this.connection?.disconnect(); }, handleError(err: Error, onConnect = false) { const notificationStore = useNotificationStore(); if (err.message == "xhr poll error") { notificationStore.push("Socket-Netzwerk-Fehler", "Reconnect Versuch in 10s", "error"); } 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"); } }, }, });