Skip to content

Commit

Permalink
Merge pull request #109 from softeerbootcamp4th/fix-chat-error
Browse files Browse the repository at this point in the history
[Fix] 서버와 채팅 메시지 타입 맞지 않아 발생했던 error 해결 & 리팩토링
  • Loading branch information
nim-od authored Aug 21, 2024
2 parents 7d8ebfb + 98f745a commit 8b9bdf7
Show file tree
Hide file tree
Showing 8 changed files with 69 additions and 62 deletions.
2 changes: 1 addition & 1 deletion packages/common/src/components/chat/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export type NoticeChatProps = {
export type MessageChatProps = {
id: string;
type: 'm';
sender: number;
sender: string;
content: string;
team: SocketCategory;
};
Expand Down
2 changes: 1 addition & 1 deletion packages/user/src/components/event/chatting/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export default function Chat({ type, team, sender, content }: ChatProps) {
case 'm':
default:
return (
<Message sender={sender} team={team} isMyMessage={me?.id === sender.toString()}>
<Message sender={sender} team={team} isMyMessage={me?.id === sender}>
{content}
</Message>
);
Expand Down
2 changes: 1 addition & 1 deletion packages/user/src/components/event/chatting/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export default function RealTimeChatting({
<Notice>{notice.content}</Notice>
<div
ref={chatListRef}
className="h-[1000px] w-full overflow-y-auto rounded-[10px] bg-neutral-800 py-10 mt-5"
className="mt-5 h-[1000px] w-full overflow-y-auto rounded-[10px] bg-neutral-800 py-10"
>
<ChatList>
{messages.map((message) => (
Expand Down
5 changes: 2 additions & 3 deletions packages/user/src/hooks/socket/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export default function useSocket() {
const chatSocket = useChatSocket();
const racingSocket = useRacingSocket();

const { onReceiveMessage, onReceiveChatList, onReceiveBlock, ...chatSocketProps } = chatSocket;
const { onReceiveMessage, onReceiveChatList, ...chatSocketProps } = chatSocket;
const { onReceiveStatus, ...racingSocketProps } = racingSocket;

const isSocketInitialized = useRef(false);
Expand All @@ -24,14 +24,13 @@ export default function useSocket() {
onReceiveChatList,
onReceiveMessage,
onReceiveStatus,
onReceiveBlock,
});
isSocketInitialized.current = true;
}
};

connetSocket();
}, [token, onReceiveMessage, onReceiveStatus, onReceiveBlock]);
}, [token, onReceiveMessage, onReceiveChatList, onReceiveStatus]);

return { chatSocket: chatSocketProps, racingSocket: racingSocketProps };
}
91 changes: 59 additions & 32 deletions packages/user/src/hooks/socket/useChatSocket.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,65 @@
import { ChatProps } from '@softeer/common/components';
import { ChatProps, NoticeChatProps } from '@softeer/common/components';
import { CHAT_SOCKET_ENDPOINTS } from '@softeer/common/constants';
import { SocketSubscribeCallbackType } from '@softeer/common/utils';
import { useCallback, useEffect, useState } from 'react';
import useChatListStorage from 'src/hooks/storage/useChatStorage.ts';
import useChatNoticeStorage from 'src/hooks/storage/useNoticeStorage.ts';
import { useCallback, useState } from 'react';
import { useToast } from 'src/hooks/useToast.ts';
import socketManager from 'src/services/socket.ts';

export type UseChatSocketReturnType = ReturnType<typeof useChatSocket>;

const INIT_NOTICE = { content: '오늘의 공지사항이 없습니다.' };
export default function useChatSocket() {
const { toast } = useToast();

const [storedChatList, storeChatList] = useChatListStorage();
const [storedNotice, storeNotice] = useChatNoticeStorage();
const [chatList, setChatList] = useState<ChatProps[]>(storedChatList);
const [notice, setNotice] = useState<Pick<NoticeChatProps, 'content'>>(INIT_NOTICE);
const [messages, setMessages] = useState<ChatProps[]>([]);

useEffect(() => storeChatList(chatList), [chatList]);
/* Helper Functions */

const handleIncomingMessage: SocketSubscribeCallbackType = useCallback(
const handleBlockData = useCallback(
(data: BlockData) => {
const { id, blockId } = data;
setMessages((prevMessages) =>
prevMessages.map((message) => (message.id === blockId ? { id, type: 'b' } : message)),
);
},
[setMessages],
);

const handleChatMessage = useCallback(
(data: ChatProps) => {
if (isNoticeData(data)) {
setNotice(data as NoticeChatProps);
} else {
setMessages((prevMessages) => [...prevMessages, data]);
}
},
[setMessages, setNotice],
);

/* Main Handlers */

const handleIncomingData: SocketSubscribeCallbackType = useCallback(
(data: unknown) => {
setChatList((prevMessages) => [...prevMessages, data] as ChatProps[]);
if (isBlockData(data)) {
handleBlockData(data);
} else {
handleChatMessage(data as ChatProps);
}
},
[setChatList],
[handleBlockData, handleChatMessage],
);

const handleIncomingBlock: SocketSubscribeCallbackType = useCallback(
const handleIncomingChatHistory: SocketSubscribeCallbackType = useCallback(
(data: unknown) => {
const { id, blockId } = data as { id: string; blockId: string };
setChatList((prevMessages) =>
prevMessages.map((message) => (message.id === blockId ? { id, type: 'b' } : message)),
);
const parsedData = Array.isArray(data) ? [...data] : ([] as ChatProps[]);
if (parsedData.length > 0 && !parsedData.at(-1)?.sender) {
const notice = { ...parsedData.pop(), type: 'n' };
setNotice(notice);
}
setMessages(parsedData);
},
[setChatList],
[setMessages],
);

const handleSendMessage = useCallback((content: string) => {
Expand All @@ -53,23 +80,23 @@ export default function useChatSocket() {
}
}, []);

const handleIncomingChatHistory: SocketSubscribeCallbackType = useCallback(
(data: unknown) => {
const parsedData = Array.isArray(data) ? [...data] : [] as ChatProps[];
if (parsedData.length > 0 && parsedData[0]?.type === 'n') {
storeNotice(parsedData.pop());
}
setChatList(parsedData);
},
[setChatList],
);

return {
onReceiveMessage: handleIncomingMessage,
onReceiveBlock: handleIncomingBlock,
onReceiveMessage: handleIncomingData,
onReceiveChatList: handleIncomingChatHistory,
onSendMessage: handleSendMessage,
messages: chatList,
notice: storedNotice
messages,
notice,
};
}

/* Helper Functions */

type BlockData = { id: string; blockId: string };

const isBlockData = (data: unknown): data is BlockData => {
return (data as BlockData).blockId !== undefined;
};

const isNoticeData = (data: ChatProps): data is NoticeChatProps => {
return data.sender === undefined;
};
7 changes: 0 additions & 7 deletions packages/user/src/hooks/storage/useChatStorage.ts

This file was deleted.

7 changes: 0 additions & 7 deletions packages/user/src/hooks/storage/useNoticeStorage.ts

This file was deleted.

15 changes: 5 additions & 10 deletions packages/user/src/services/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ class SocketManager {

private onReceiveMessage: SocketSubscribeCallbackType | null = null;

private onReceiveBlock: SocketSubscribeCallbackType | null = null;

private onReceiveChatList: SocketSubscribeCallbackType | null = null;

private onReceiveStatus: SocketSubscribeCallbackType | null = null;
Expand All @@ -25,21 +23,18 @@ class SocketManager {
async connectSocketClient({
token,
onReceiveMessage,
onReceiveBlock,
onReceiveStatus,
onReceiveChatList,
}: {
token: string | null | undefined;
onReceiveMessage: SocketSubscribeCallbackType;
onReceiveBlock: SocketSubscribeCallbackType;
onReceiveStatus: SocketSubscribeCallbackType;
onReceiveChatList: SocketSubscribeCallbackType;
}) {
this.initializeSocketClient(token);

this.onReceiveChatList = onReceiveChatList;
this.onReceiveMessage = onReceiveMessage;
this.onReceiveBlock = onReceiveBlock;
this.onReceiveStatus = onReceiveStatus;

try {
Expand All @@ -60,7 +55,6 @@ class SocketManager {
async reconnectSocketClient(token?: string | null) {
await this.connectSocketClient({
token,
onReceiveBlock: this.onReceiveBlock!,
onReceiveMessage: this.onReceiveMessage!,
onReceiveStatus: this.onReceiveStatus!,
onReceiveChatList: this.onReceiveChatList!,
Expand Down Expand Up @@ -91,12 +85,13 @@ class SocketManager {
destination: CHAT_SOCKET_ENDPOINTS.SUBSCRIBE_MESSAGE,
callback: this.onReceiveMessage,
});
}

if (this.onReceiveBlock) {
this.socketClient.subscribe({
destination: CHAT_SOCKET_ENDPOINTS.SUBSCRIBE_NOTICE,
callback: this.onReceiveMessage,
});
this.socketClient.subscribe({
destination: CHAT_SOCKET_ENDPOINTS.SUBSCRIBE_BLOCK,
callback: this.onReceiveBlock,
callback: this.onReceiveMessage,
});
}

Expand Down

0 comments on commit 8b9bdf7

Please sign in to comment.