File size: 1,446 Bytes
c0a9bce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
export interface ConnectionStatus {
  connected: boolean;
  latency: number;
  lastChecked: string;
}

export const checkConnection = async (): Promise<ConnectionStatus> => {
  try {
    // Check if we have network connectivity
    const online = navigator.onLine;

    if (!online) {
      return {
        connected: false,
        latency: 0,
        lastChecked: new Date().toISOString(),
      };
    }

    // Try multiple endpoints in case one fails
    const endpoints = [
      '/api/health',
      '/', // Fallback to root route
      '/favicon.ico', // Another common fallback
    ];

    let latency = 0;
    let connected = false;

    for (const endpoint of endpoints) {
      try {
        const start = performance.now();
        const response = await fetch(endpoint, {
          method: 'HEAD',
          cache: 'no-cache',
        });
        const end = performance.now();

        if (response.ok) {
          latency = Math.round(end - start);
          connected = true;
          break;
        }
      } catch (endpointError) {
        console.debug(`Failed to connect to ${endpoint}:`, endpointError);
        continue;
      }
    }

    return {
      connected,
      latency,
      lastChecked: new Date().toISOString(),
    };
  } catch (error) {
    console.error('Connection check failed:', error);
    return {
      connected: false,
      latency: 0,
      lastChecked: new Date().toISOString(),
    };
  }
};