All files / src/hooks/use-chat/use-chat-list-socket index.ts

17.56% Statements 13/74
100% Branches 0/0
0% Functions 0/1
17.56% Lines 13/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 751x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                            
import { useEffect, useRef } from 'react';
 
import { Client, IMessage, StompSubscription } from '@stomp/stompjs';
import { useQueryClient } from '@tanstack/react-query';
import SockJS from 'sockjs-client';
 
interface UseChatListSocketOptions {
  userId: number;
  accessToken: string | null;
  chatRoomIds: number[]; // 구독할 채팅방 ID 목록
}
 
export const useChatListSocket = ({
  userId,
  accessToken,
  chatRoomIds,
}: UseChatListSocketOptions) => {
  const clientRef = useRef<Client | null>(null);
  const queryClient = useQueryClient();
  const subscriptionsRef = useRef<Map<number, StompSubscription>>(new Map());

  useEffect(() => {
    if (!accessToken || chatRoomIds.length === 0) return;

    const client = new Client({
      webSocketFactory: () => {
        const socket = new SockJS(`${process.env.NEXT_PUBLIC_API_BASE_URL}/ws-chat`, null, {
          transports: ['websocket'],
        });
        return socket;
      },
      connectHeaders: {
        Authorization: `Bearer ${accessToken}`,
      },
      reconnectDelay: 6000,
      heartbeatIncoming: 4000,
      heartbeatOutgoing: 4000,
    });

    client.onConnect = () => {
      if (process.env.NODE_ENV === 'development') {
        console.log('✅ Chat list socket connected');
      }
      // 모든 채팅방 구독
      chatRoomIds.forEach((roomId) => {
        const subscription = client.subscribe(`/sub/chat/room/${roomId}`, (message: IMessage) => {
          const payload = JSON.parse(message.body);
          if (process.env.NODE_ENV === 'development') {
            console.log('🔔 새 메시지 수신:', payload);
          }
          // 채팅 목록 갱신
          queryClient.invalidateQueries({
            queryKey: ['chatList', userId],
            exact: true,
          });
        });

        subscriptionsRef.current.set(roomId, subscription);
      });
    };

    client.activate();
    clientRef.current = client;

    return () => {
      // 모든 구독 해제
      subscriptionsRef.current.forEach((subscription) => {
        subscription.unsubscribe();
      });
      subscriptionsRef.current.clear();
      client.deactivate();
    };
  }, [userId, accessToken, chatRoomIds, queryClient]);
};