74 lines
1.8 KiB
TypeScript
74 lines
1.8 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
|
import { io, type Socket } 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 socketRef = useRef<Socket | null>(null);
|
|
const onEventRef = useRef(onEvent);
|
|
const [connectionStatus, setConnectionStatus] =
|
|
useState<ConnectionStatus>('idle');
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
useEffect(() => {
|
|
onEventRef.current = onEvent;
|
|
}, [onEvent]);
|
|
|
|
useEffect(() => {
|
|
if (!puuid && !parentJobId) {
|
|
setConnectionStatus('idle');
|
|
return;
|
|
}
|
|
|
|
setConnectionStatus('connecting');
|
|
setError(null);
|
|
|
|
const socket = io(`${API_BASE_URL}/riot-refresh`, {
|
|
transports: ['websocket'],
|
|
});
|
|
socketRef.current = socket;
|
|
|
|
socket.on('connect', () => {
|
|
setConnectionStatus('connected');
|
|
socket.emit('subscribe', { puuid, parentJobId });
|
|
});
|
|
|
|
socket.on('disconnect', () => {
|
|
setConnectionStatus('disconnected');
|
|
});
|
|
|
|
socket.on('riot-refresh', (event: ApiRiotRefreshEvent) => {
|
|
onEventRef.current(event);
|
|
});
|
|
|
|
socket.on('error', (payload: { message?: string }) => {
|
|
setConnectionStatus('error');
|
|
setError(payload.message ?? '전적 갱신 소켓 연결 중 오류가 발생했습니다.');
|
|
});
|
|
|
|
return () => {
|
|
socket.removeAllListeners();
|
|
socket.disconnect();
|
|
socketRef.current = null;
|
|
setConnectionStatus('idle');
|
|
};
|
|
}, [parentJobId, puuid]);
|
|
|
|
return { connectionStatus, error };
|
|
}
|