All files / apps/host/src/hooks useWebSocket.ts

68.35% Statements 54/79
33.33% Branches 8/24
66.66% Functions 12/18
70.27% Lines 52/74

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144                3x   3x 11x 11x 11x 11x 11x   11x   11x 11x   11x 5x           11x                             11x 5x 5x   5x 4x 4x     5x     11x 4x 4x 4x   4x         4x   4x   4x   4x 4x   4x 1x 1x     4x 1x 1x 1x           4x       4x                     11x 4x 1x   1x           1x 1x       4x     11x 4x 4x   4x 4x       11x                        
import { useCallback, useEffect, useRef, useState } from 'react';
import { AppState, AppStateStatus } from 'react-native';
import { getAuth, getIdToken } from '@react-native-firebase/auth';
 
import { FLASH_WS_URL } from '@/constants/apis';
 
type WSStatus = 'idle' | 'connecting' | 'connected' | 'reconnecting' | 'closed';
 
const MAX_RECONNECT_DELAY = 30_000;
 
export const useWebSocketListener = () => {
  const wsRef = useRef<WebSocket | null>(null);
  const reconnectTimerRef = useRef<NodeJS.Timeout | null>(null);
  const reconnectAttemptRef = useRef(0);
  const shouldReconnectRef = useRef(true);
  const appStateRef = useRef<AppStateStatus>('active');
 
  const connectRef = useRef<() => Promise<void>>(async () => {});
 
  const [status, setStatus] = useState<WSStatus>('idle');
  const [lastMessage, setLastMessage] = useState<any>(null);
 
  const clearReconnectTimer = () => {
    Iif (reconnectTimerRef.current) {
      clearTimeout(reconnectTimerRef.current);
      reconnectTimerRef.current = null;
    }
  };
 
  const scheduleReconnect = useCallback(() => {
    if (!shouldReconnectRef.current) return;
    if (appStateRef.current !== 'active') return;
 
    reconnectAttemptRef.current += 1;
 
    const delay = Math.min(1000 * Math.pow(2, reconnectAttemptRef.current), MAX_RECONNECT_DELAY);
 
    setStatus('reconnecting');
 
    reconnectTimerRef.current = setTimeout(() => {
      connectRef.current();
    }, delay);
  }, []);
 
  const disconnect = useCallback(() => {
    shouldReconnectRef.current = false;
    clearReconnectTimer();
 
    if (wsRef.current) {
      wsRef.current.close();
      wsRef.current = null;
    }
 
    setStatus('closed');
  }, []);
 
  connectRef.current = async () => {
    try {
      const auth = getAuth();
      const user = auth.currentUser;
 
      Iif (!user) {
        console.warn('[WS] No Firebase user, skip connect');
        return;
      }
 
      setStatus(prev => (prev === 'connected' ? prev : 'connecting'));
 
      const token = await getIdToken(user);
 
      Iif (!shouldReconnectRef.current) return;
 
      const ws = new WebSocket(`${FLASH_WS_URL}?token=${encodeURIComponent(token)}`);
      wsRef.current = ws;
 
      ws.onopen = () => {
        reconnectAttemptRef.current = 0;
        setStatus('connected');
      };
 
      ws.onmessage = event => {
        try {
          const data = JSON.parse(event.data);
          setLastMessage(data);
        } catch {
          console.warn('[WS] Non-JSON message:', event.data);
        }
      };
 
      ws.onerror = e => {
        console.warn('[WS] Error', e);
      };
 
      ws.onclose = () => {
        wsRef.current = null;
        setStatus('closed');
        scheduleReconnect();
      };
    } catch (err) {
      console.error('[WS] Connect error', err);
      scheduleReconnect();
    }
  };
 
  useEffect(() => {
    const sub = AppState.addEventListener('change', nextState => {
      appStateRef.current = nextState;
 
      Iif (nextState === 'active') {
        if (!wsRef.current && shouldReconnectRef.current) {
          connectRef.current();
        }
      }
 
      Eif (nextState === 'background') {
        wsRef.current?.close();
      }
    });
 
    return () => sub.remove();
  }, []);
 
  useEffect(() => {
    shouldReconnectRef.current = true;
    connectRef.current();
 
    return () => {
      disconnect();
    };
  }, [disconnect]);
 
  return {
    status,
    connected: status === 'connected',
    lastMessage,
    send: (data: any) => {
      if (wsRef.current?.readyState === WebSocket.OPEN) {
        wsRef.current.send(JSON.stringify(data));
      }
    },
    disconnect,
  };
};