180 lines
4.8 KiB
TypeScript
180 lines
4.8 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
|
import { io, type Socket } from 'socket.io-client';
|
|
import { API_BASE_URL, useAuthUserId } from '../config';
|
|
import { acquireAccessToken } from '../lib/auth/token-provider';
|
|
import type { ApiAuction, ApiAuctionChatMessage, Position } from './types';
|
|
|
|
type ConnectionStatus =
|
|
| 'idle'
|
|
| 'connecting'
|
|
| 'connected'
|
|
| 'disconnected'
|
|
| 'error';
|
|
|
|
interface BidPayload {
|
|
teamIndex: number;
|
|
amount: number;
|
|
bidderUserId?: string;
|
|
}
|
|
|
|
interface ChatMessagePayload {
|
|
displayName?: string;
|
|
message: string;
|
|
}
|
|
|
|
interface ChatHistoryPayload {
|
|
messages?: ApiAuctionChatMessage[];
|
|
}
|
|
|
|
interface ResetPayload {
|
|
matchId?: string;
|
|
}
|
|
|
|
const MAX_CHAT_MESSAGES = 200;
|
|
|
|
function mergeChatMessages(
|
|
current: ApiAuctionChatMessage[],
|
|
incoming: ApiAuctionChatMessage[],
|
|
) {
|
|
const byId = new Map(current.map((message) => [message.id, message]));
|
|
for (const message of incoming) {
|
|
byId.set(message.id, message);
|
|
}
|
|
|
|
return [...byId.values()]
|
|
.sort((left, right) => Date.parse(left.sentAt) - Date.parse(right.sentAt))
|
|
.slice(-MAX_CHAT_MESSAGES);
|
|
}
|
|
|
|
export function useAuctionSocket(matchId: string | undefined) {
|
|
const authUserId = useAuthUserId();
|
|
const socketRef = useRef<Socket | null>(null);
|
|
const [auction, setAuction] = useState<ApiAuction | null>(null);
|
|
const [chatMessages, setChatMessages] = useState<ApiAuctionChatMessage[]>([]);
|
|
const [resetAt, setResetAt] = useState<number | null>(null);
|
|
const [connectionStatus, setConnectionStatus] =
|
|
useState<ConnectionStatus>('idle');
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
useEffect(() => {
|
|
if (!matchId) {
|
|
return;
|
|
}
|
|
|
|
let disposed = false;
|
|
setConnectionStatus('connecting');
|
|
setError(null);
|
|
|
|
void (async () => {
|
|
const accessToken = await acquireAccessToken().catch((error) => {
|
|
console.warn('Failed to acquire socket access token:', error);
|
|
return null;
|
|
});
|
|
if (disposed) return;
|
|
|
|
const socket = io(`${API_BASE_URL}/auction`, {
|
|
transports: ['websocket'],
|
|
auth: accessToken
|
|
? { token: accessToken }
|
|
: authUserId
|
|
? { 'x-auth-user-id': authUserId }
|
|
: {},
|
|
});
|
|
|
|
socketRef.current = socket;
|
|
|
|
socket.on('connect', () => {
|
|
setConnectionStatus('connected');
|
|
socket.emit('join', { matchId });
|
|
});
|
|
|
|
socket.on('disconnect', () => {
|
|
setConnectionStatus('disconnected');
|
|
});
|
|
|
|
socket.on('state', (nextAuction: ApiAuction) => {
|
|
setAuction(nextAuction);
|
|
if (nextAuction.chatMessages) {
|
|
setChatMessages(mergeChatMessages([], nextAuction.chatMessages));
|
|
}
|
|
setError(null);
|
|
});
|
|
|
|
socket.on('chat-history', (payload: ChatHistoryPayload) => {
|
|
setChatMessages(mergeChatMessages([], payload.messages ?? []));
|
|
});
|
|
|
|
socket.on('chat-message', (message: ApiAuctionChatMessage) => {
|
|
setChatMessages((current) => mergeChatMessages(current, [message]));
|
|
});
|
|
|
|
socket.on('reset', (payload: ResetPayload) => {
|
|
if (payload.matchId && payload.matchId !== matchId) return;
|
|
setAuction(null);
|
|
setChatMessages([]);
|
|
setResetAt(Date.now());
|
|
setError('경매가 취소되었습니다.');
|
|
});
|
|
|
|
socket.on('error', (payload: { message?: string }) => {
|
|
setConnectionStatus('error');
|
|
setError(payload.message ?? '실시간 경매 연결 중 오류가 발생했습니다.');
|
|
});
|
|
})();
|
|
|
|
return () => {
|
|
disposed = true;
|
|
const socket = socketRef.current;
|
|
socket?.removeAllListeners();
|
|
socket?.disconnect();
|
|
socketRef.current = null;
|
|
setConnectionStatus('idle');
|
|
};
|
|
}, [authUserId, matchId]);
|
|
|
|
function emit(eventName: string, payload?: unknown) {
|
|
const socket = socketRef.current;
|
|
if (!socket || !socket.connected) {
|
|
setError('소켓이 아직 연결되지 않았습니다.');
|
|
return;
|
|
}
|
|
|
|
setError(null);
|
|
|
|
if (payload === undefined) {
|
|
socket.emit(eventName);
|
|
return;
|
|
}
|
|
|
|
socket.emit(eventName, payload);
|
|
}
|
|
|
|
const visibleAuction = auction?.matchId === matchId ? auction : null;
|
|
const visibleConnectionStatus: ConnectionStatus = matchId
|
|
? connectionStatus
|
|
: 'idle';
|
|
|
|
return {
|
|
auction: visibleAuction,
|
|
chatMessages: visibleAuction ? chatMessages : [],
|
|
resetAt,
|
|
connectionStatus: visibleConnectionStatus,
|
|
error,
|
|
placeBid(payload: BidPayload) {
|
|
emit('bid', payload);
|
|
},
|
|
openBidding() {
|
|
emit('open-bidding', {});
|
|
},
|
|
markSold(assignedPosition?: Position) {
|
|
emit('sold', assignedPosition ? { assignedPosition } : {});
|
|
},
|
|
next() {
|
|
emit('next', {});
|
|
},
|
|
sendChatMessage(payload: ChatMessagePayload) {
|
|
emit('chat-message', payload);
|
|
},
|
|
};
|
|
}
|