File size: 1,171 Bytes
780df80
 
 
7d94a77
780df80
63ec0ab
 
 
 
 
780df80
63ec0ab
780df80
 
 
 
63ec0ab
780df80
 
 
 
 
7d94a77
 
 
 
 
 
 
 
 
 
 
 
780df80
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { io, Socket } from "socket.io-client";

let socket: Socket | null = null;
let eventSource: EventSource | null = null;

export const initializeSocket = (url?: string) => {
  // In production (Docker), use the same host where the frontend is served
  // This will route through nginx proxy to the backend
  const socketUrl = url || process.env.NEXT_PUBLIC_KNET_BACKEND || (typeof window !== 'undefined' ? window.location.origin : "http://127.0.0.1:3000");

  if (!socket) {
    socket = io(socketUrl, {
      transports: ["websocket"],
      reconnection: true,
      reconnectionAttempts: 5,
      reconnectionDelay: 1000,
      path: "/socket.io/",
    });
  }
  return socket;
};

export const initializeSse = (url: string) => {
  eventSource = new EventSource(url);
  return eventSource;
};

export const closeSse = () => {
  if (eventSource) {
    eventSource.close();
    eventSource = null;
  }
};

export const getSocket = () => {
  if (!socket) {
    throw new Error("Socket not initialized. Call initializeSocket first.");
  }
  return socket;
};

export const disconnectSocket = () => {
  if (socket) {
    socket.disconnect();
    socket = null;
  }
};