All files / packages/hooks/src useWebSocketListener.ts

89.15% Statements 74/83
65.62% Branches 21/32
88.88% Functions 16/18
92.3% Lines 72/78

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 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165                                            1x   1x 12x 12x 12x 12x 12x 12x   12x   12x 12x   12x 5x 1x 1x       12x 1x 1x   1x 1x         1x   1x         12x 5x 5x   5x 3x 3x     5x     12x 4x 4x 4x         4x   4x 4x 1x 1x 1x       4x   4x 4x   4x 1x 1x     4x 2x 2x 1x   1x       4x 1x     4x 1x 1x 1x               12x 4x 2x   2x 1x         2x 1x       4x     12x 4x 4x   4x 4x       12x         1x 1x            
import { useCallback, useEffect, useRef, useState } from "react";
import { AppState, AppStateStatus } from "react-native";
 
export type WSStatus =
  | "idle"
  | "connecting"
  | "connected"
  | "reconnecting"
  | "closed";
 
export interface WSMessage {
  type: string;
  channel?: string;
  payload?: any;
  data?: unknown;
}
 
export interface UseWebSocketOptions {
  url?: string;
  getToken?: () => Promise<string | null>;
}
 
const MAX_RECONNECT_DELAY = 30_000;
 
export const useWebSocketListener = (options?: UseWebSocketOptions) => {
  const { url, getToken } = options || {};
  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<WSMessage | null>(null);
 
  const clearReconnectTimer = () => {
    if (reconnectTimerRef.current) {
      clearTimeout(reconnectTimerRef.current);
      reconnectTimerRef.current = null;
    }
  };
 
  const scheduleReconnect = useCallback(() => {
    Iif (!shouldReconnectRef.current) return;
    Iif (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 targetUrl = url || (process.env as any).FLASH_WS_URL;
      Iif (!targetUrl) {
        console.warn("[WS] No WebSocket URL provided, skip connect");
        return;
      }
 
      setStatus((prev) => (prev === "connected" ? prev : "connecting"));
 
      let tokenParam = "";
      if (getToken) {
        const token = await getToken();
        Eif (token) {
          tokenParam = `?token=${encodeURIComponent(token)}`;
        }
      }
 
      Iif (!shouldReconnectRef.current) return;
 
      const ws = new WebSocket(`${targetUrl}${tokenParam}`);
      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;
 
      if (nextState === "active") {
        Iif (!wsRef.current && shouldReconnectRef.current) {
          connectRef.current();
        }
      }
 
      if (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: WSMessage) => {
      Eif (wsRef.current?.readyState === WebSocket.OPEN) {
        wsRef.current.send(JSON.stringify(data));
      }
    },
    disconnect,
  };
};