فهرست منبع

fix: make WebSocket URLs dynamic and improve reconnection logic

unknown 2 ماه پیش
والد
کامیت
b58c4e5385
3فایلهای تغییر یافته به همراه19 افزوده شده و 6 حذف شده
  1. 2 1
      src/components/OrderChat.vue
  2. 9 0
      src/lib/utils.ts
  3. 8 5
      src/stores/auth.ts

+ 2 - 1
src/components/OrderChat.vue

@@ -92,7 +92,7 @@ import { MessageCircle, Send, Loader2, ShieldCheck, X, Eye } from "lucide-vue-ne
 import { getOrderMessages, sendOrderMessage } from "@/lib/api";
 import { useAuthStore } from "@/stores/auth";
 
-const WS_BASE_URL = import.meta.env.VITE_WS_URL || "ws://localhost:8000";
+import { getWsUrl } from "@/lib/utils";
 
 const props = defineProps<{
   orderId: number;
@@ -138,6 +138,7 @@ function connectWebSocket() {
   const token = localStorage.getItem("token");
   if (!token) return;
 
+  const WS_BASE_URL = getWsUrl();
   ws = new WebSocket(`${WS_BASE_URL}/chat?token=${encodeURIComponent(token)}&order_id=${props.orderId}`);
 
   ws.onopen = () => {

+ 9 - 0
src/lib/utils.ts

@@ -4,3 +4,12 @@ import { twMerge } from "tailwind-merge";
 export function cn(...inputs: ClassValue[]) {
   return twMerge(clsx(inputs));
 }
+
+export function getWsUrl() {
+  const envUrl = import.meta.env.VITE_WS_URL;
+  if (envUrl && !envUrl.includes('localhost')) return envUrl;
+  
+  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
+  const host = window.location.host;
+  return `${protocol}//${host}`;
+}

+ 8 - 5
src/stores/auth.ts

@@ -1,6 +1,7 @@
 import { defineStore } from "pinia";
 import { ref } from "vue";
 import { getCurrentUser } from "@/lib/api";
+import { getWsUrl } from "@/lib/utils";
 import { toast } from "vue-sonner";
 
 export const useAuthStore = defineStore("auth", () => {
@@ -32,11 +33,9 @@ export const useAuthStore = defineStore("auth", () => {
   let pingInterval: number | null = null;
   const unreadMessagesCount = ref(0);
 
-
-
   let globalWs: WebSocket | null = null;
   let reconnectTimer: number | null = null;
-  const WS_BASE_URL = import.meta.env.VITE_WS_URL || "ws://localhost:8000";
+  const WS_BASE_URL = getWsUrl();
 
   // ── Audio ──────────────────────────────────────────────────────────────────
   // Single shared AudioContext, created lazily on first user gesture.
@@ -200,8 +199,12 @@ export const useAuthStore = defineStore("auth", () => {
         return;
       }
 
-      if (user.value && !wsAuthFailed.value) { // If still logged in and no auth error, try reconnecting
-        reconnectTimer = window.setTimeout(startPing, 5000);
+      if (user.value) { 
+        // If still logged in, try reconnecting. 
+        // We only don't reconnect if wsAuthFailed is set during onclose for specific codes.
+        if (!wsAuthFailed.value) {
+          reconnectTimer = window.setTimeout(startPing, 5000);
+        }
       }
     };