import { useEffect, useRef, useState } from 'react'; import { io } from 'socket.io-client'; import { API_BASE_URL } from '../config'; import type { ApiRiotRefreshEvent } from './types'; type ConnectionStatus = | 'idle' | 'connecting' | 'connected' | 'disconnected' | 'error'; export function useRiotRefreshSocket({ puuid, parentJobId, onEvent, }: { puuid?: string; parentJobId?: string; onEvent: (event: ApiRiotRefreshEvent) => void; }) { const subscriptionKey = puuid || parentJobId ? JSON.stringify([puuid, parentJobId]) : null; const onEventRef = useRef(onEvent); const [connectionState, setConnectionState] = useState<{ key: string; status: ConnectionStatus; error: string | null; }>({ key: '', status: 'idle', error: null }); useEffect(() => { onEventRef.current = onEvent; }, [onEvent]); useEffect(() => { if (!subscriptionKey) { return; } const socket = io(`${API_BASE_URL}/riot-refresh`, { transports: ['websocket'], }); socket.on('connect', () => { setConnectionState({ key: subscriptionKey, status: 'connected', error: null, }); socket.emit('subscribe', { puuid, parentJobId }); }); socket.on('disconnect', () => { setConnectionState((current) => ({ key: subscriptionKey, status: 'disconnected', error: current.key === subscriptionKey ? current.error : null, })); }); socket.on('riot-refresh', (event: ApiRiotRefreshEvent) => { onEventRef.current(event); }); socket.on('error', (payload: { message?: string }) => { setConnectionState({ key: subscriptionKey, status: 'error', error: payload.message ?? '전적 갱신 소켓 연결 중 오류가 발생했습니다.', }); }); return () => { socket.removeAllListeners(); socket.disconnect(); }; }, [parentJobId, puuid, subscriptionKey]); const hasCurrentConnection = subscriptionKey !== null && connectionState.key === subscriptionKey; return { connectionStatus: subscriptionKey === null ? 'idle' : hasCurrentConnection ? connectionState.status : 'connecting', error: hasCurrentConnection ? connectionState.error : null, }; }