Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature][Task-42] Notice, Block 송수신 방식 수정 #93

Merged
merged 5 commits into from
Aug 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/admin/src/components/chat/Chat.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { BlockedChat, ChatProps, Message, Notice } from '@softeer/common/components';
import { FunctionComponent, useCallback } from 'react';
import { Button } from '../ui/button.tsx';
import { Button } from '../ui/button.js';

type AdminChatProps = {
onBlock: (id: string) => void
Expand Down
31 changes: 17 additions & 14 deletions packages/admin/src/components/chat/RealTimeChatting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,39 @@ import { ChatList } from '@softeer/common/components';
import { useRef } from 'react';
import { AdminSocketReturnType } from 'src/hooks/socket/index.ts';
import { useAlert } from 'src/store/provider/AlertProvider.tsx';
import { Button } from '../ui/button.tsx';
import { Input } from '../ui/input.tsx';
import Chat from './Chat.tsx';
import { Button } from '../ui/button.js';
import { Input } from '../ui/input.js';
import Chat from './Chat.js';

/** 실시간 기대평 섹션 */

function RealTimeChatting({ chatSocket: { messages, onBlock, onNotice } }: Pick<AdminSocketReturnType, 'chatSocket'>) {
function RealTimeChatting({
chatSocket: { messages, onBlock, onNotice, notice },
}: Pick<AdminSocketReturnType, 'chatSocket'>) {
const { openAlert, addAlertCallback } = useAlert();

const noticeInputRef = useRef<HTMLInputElement>(null);
const handleSend: React.FormEventHandler<HTMLFormElement> = (event) => {
event.preventDefault();
if (noticeInputRef.current) {
const { value } = noticeInputRef!.current!;
if (value !== '') {
addAlertCallback(() => {
if (noticeInputRef.current) {
onNotice(noticeInputRef.current.value);
noticeInputRef.current.value = '';
}
onNotice(value);
});
openAlert(<p>정말로 전송하겠습니까?<br />전송 이후엔 수정이 불가능합니다.</p>, 'confirm');
openAlert('공지사항을 업데이트 합니다.', 'confirm');
} else {
openAlert(<p>공지사항을 입력하세요.</p>, 'alert');
openAlert('공지사항을 입력하세요.', 'alert');
}
};

return (
<section className="container flex max-w-[1200px] snap-start flex-col items-center pb-[115px] pt-[50px]">
<form className="flex w-full flex-row mb-4 gap-2" onSubmit={handleSend}>
<form className="mb-4 flex w-full flex-row gap-2" onSubmit={handleSend}>
<Input ref={noticeInputRef} className="flex flex-1" placeholder="공지사항을 입력하세요." />
<Button type="submit">공지사항 전송</Button>
<Button type="submit">공지사항 변경</Button>
</form>
<div className="rounded-4 mb-4 w-full border-2 border-yellow-900 p-6">
공지사항 : {notice}
</div>
<div className="h-[1000px] w-full overflow-y-auto rounded-[10px] bg-neutral-800 py-10">
<ChatList>
{messages.map((message) => (
Expand Down
2 changes: 1 addition & 1 deletion packages/admin/src/constants/api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { API_BASE_URL } from './environments.ts';
import { API_BASE_URL } from './environments.js';

export const BASE_URL = API_BASE_URL;

Expand Down
3 changes: 1 addition & 2 deletions packages/admin/src/hooks/socket/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@ import { ACCESS_TOKEN_KEY } from '@softeer/common/constants';
import { Cookie } from '@softeer/common/utils';
import { useEffect } from 'react';
import socketManager from 'src/services/socket.ts';
import useChatSocket from './useChatSocket.ts';
import useChatSocket from './useChatSocket.js';

export type AdminSocketReturnType = ReturnType<typeof useSocket>;

export default function useSocket() {
const accessToken = Cookie.getCookie<string>(ACCESS_TOKEN_KEY) ?? '';
const chatSocket = useChatSocket();

const { onReceiveMessage, onReceiveBlock, onReceiveNotice, ...chatSocketProps } = chatSocket;
useEffect(() => {
if (accessToken !== '') {
Expand Down
32 changes: 14 additions & 18 deletions packages/admin/src/hooks/socket/useChatSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,23 @@ export default function useChatSocket() {
const socketClient = socketManager.getSocketClient();

const [chatMessages, setChatMessages] = useState<ChatProps[]>([]);
const [notice, setNotice] = useState<string>('');

const handleIncomingMessage: SocketSubscribeCallbackType = useCallback(
(data: unknown, messageId: string) => {
const parsedData = data as Omit<ChatProps, 'id'>;
const parsedMessage = { id: messageId, ...parsedData };
setChatMessages((prevMessages) => [...prevMessages, parsedMessage] as ChatProps[]);
},
[],
);
const handleIncomingMessage: SocketSubscribeCallbackType = useCallback((data: unknown) => {
setChatMessages((prevMessages) => [...prevMessages, data] as ChatProps[]);
}, []);

const handleIncomintBlock: SocketSubscribeCallbackType = useCallback(
(data: unknown) => {
const { blockId } = data as { blockId: string };
setChatMessages(prevMessages => {
setChatMessages((prevMessages) => {
const tmpMessages = prevMessages.slice();
tmpMessages.some((tmpMessage, index) => {
if (tmpMessage.id === blockId) {
tmpMessages[index].type = 'b';
return true;
} return false;
}
return false;
});
return tmpMessages;
});
Expand All @@ -41,12 +38,11 @@ export default function useChatSocket() {
);

const handleIncomingNotice: SocketSubscribeCallbackType = useCallback(
(data: unknown, messageId: string) => {
const parsedData = data as Omit<ChatProps, 'id'>;
const parsedMessage = { id: messageId, ...parsedData };
setChatMessages((prevMessages) => [...prevMessages, parsedMessage] as ChatProps[]);
(data: unknown) => {
const { content } = data as { content: string };
setNotice(content);
},
[],
[socketClient],
);

const handleBlock = useCallback(
Expand All @@ -56,7 +52,7 @@ export default function useChatSocket() {
};
try {
socketClient.sendMessages({
destination: CHAT_SOCKET_ENDPOINTS.BLOCK,
destination: CHAT_SOCKET_ENDPOINTS.PUBLISH_BLOCK,
body: blockId,
});
} catch (error) {
Expand All @@ -71,9 +67,8 @@ export default function useChatSocket() {
(content: string) => {
try {
const chatMessage = { content };

socketClient.sendMessages({
destination: CHAT_SOCKET_ENDPOINTS.NOTICE,
destination: CHAT_SOCKET_ENDPOINTS.PUBLISH_NOTICE,
body: chatMessage,
});
} catch (error) {
Expand All @@ -91,5 +86,6 @@ export default function useChatSocket() {
onBlock: handleBlock,
onNotice: handleSendNotice,
messages: chatMessages,
notice,
};
}
2 changes: 1 addition & 1 deletion packages/admin/src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import ReactDOM from 'react-dom/client';
import App from './App.tsx';
import App from './App.js';
import './styles/index.css';

ReactDOM.createRoot(document.getElementById('root')!).render(<App />);
68 changes: 27 additions & 41 deletions packages/admin/src/services/socket.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,32 @@
import { CHAT_SOCKET_ENDPOINTS, RACING_SOCKET_ENDPOINTS } from '@softeer/common/constants';
import { Socket, SocketSubscribeCallbackType } from '@softeer/common/utils';
import { ACCESS_TOKEN_KEY, CHAT_SOCKET_ENDPOINTS } from '@softeer/common/constants';
import { Cookie, Socket, SocketSubscribeCallbackType } from '@softeer/common/utils';
import { SOCKET_BASE_URL } from 'src/constants/environments.ts';
// import CustomError from 'src/utils/error.ts';

class SocketManager {
private static instance: SocketManager | null = null;

private socketClient: Socket | null = null;

private onReceiveMessage: SocketSubscribeCallbackType | null = null;

private onReceiveStatus: SocketSubscribeCallbackType | null = null;

private onReceiveBlock: SocketSubscribeCallbackType | null = null;

private onReceiveNotice: SocketSubscribeCallbackType | null = null;

private constructor() {
this.initializeSocketClient();
constructor(token: string | null) {
this.initializeSocketClient(token);
}

public static getInstance() {
if (!SocketManager.instance) {
SocketManager.instance = new SocketManager();
}
return SocketManager.instance;
public getSocketClient() {
return this.socketClient!;
}

private initializeSocketClient(token?: string | null) {
this.socketClient = new Socket(SOCKET_BASE_URL, token);
}

public getSocketClient() {
return this.socketClient!;
if (token) {
this.socketClient = new Socket(SOCKET_BASE_URL, token);
}
}

connectSocketClient({
async connectSocketClient({
token,
onReceiveMessage,
onReceiveBlock,
Expand All @@ -46,26 +37,26 @@ class SocketManager {
onReceiveBlock: SocketSubscribeCallbackType;
onReceiveNotice: SocketSubscribeCallbackType;
}) {
if (this.socketClient) {
await this.socketClient.disconnect();
}

this.initializeSocketClient(token);

this.onReceiveMessage = onReceiveMessage;
this.onReceiveBlock = onReceiveBlock;
this.onReceiveNotice = onReceiveNotice;

this.socketClient!.connect((isConnected) => {
if (isConnected) {
this.subscribeToTopics();
} else {
// throw new CustomError('서버에서 데이터를 불러오는 데 실패했습니다.', 500);
}
});
try {
await this.socketClient!.connect();
this.subscribeToTopics();
} catch (error) {
throw new Error('서버에서 데이터를 불러오는 데 실패했습니다.');
}
}

reconnectSocketClient(token?: string | null) {
if (this.socketClient) {
this.socketClient.disconnect();
}
this.connectSocketClient({
async reconnectSocketClient(token?: string | null) {
await this.connectSocketClient({
token,
onReceiveBlock: this.onReceiveBlock!,
onReceiveMessage: this.onReceiveMessage!,
Expand All @@ -77,31 +68,26 @@ class SocketManager {
if (this.socketClient) {
if (this.onReceiveMessage) {
this.socketClient.subscribe({
destination: CHAT_SOCKET_ENDPOINTS.SUBSCRIBE,
destination: CHAT_SOCKET_ENDPOINTS.SUBSCRIBE_CHAT,
callback: this.onReceiveMessage,
});
}
if (this.onReceiveStatus) {
this.socketClient.subscribe({
destination: RACING_SOCKET_ENDPOINTS.SUBSCRIBE,
callback: this.onReceiveStatus,
});
}

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

const socketManager = SocketManager.getInstance();
const socketManager = new SocketManager(Cookie.getCookie(ACCESS_TOKEN_KEY));
export default socketManager;
10 changes: 6 additions & 4 deletions packages/common/src/constants/socket.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { Category, SocketCategory } from 'src/types/category.ts';

export const CHAT_SOCKET_ENDPOINTS = {
SUBSCRIBE: '/topic/chat',
PUBLISH: '/app/chat.sendMessage',
BLOCK: '/topic/block',
NOTICE: '/app/chat.sendNotice',
SUBSCRIBE_CHAT: '/topic/chat',
PUBLISH_CHAT: '/app/chat.sendMessage',
SUBSCRIBE_BLOCK: '/topic/block',
PUBLISH_BLOCK: '/app/chat.sendBlock',
SUBSCRIBE_NOTICE: '/topic/notice',
PUBLISH_NOTICE: '/app/chat.sendNotice',
SUBSCRIBE_CHAT_LIST: '/user/queue/chatHistory',
PUBLISH_CHAT_LIST: '/app/chat.getHistory',
} as const;
Expand Down
2 changes: 1 addition & 1 deletion packages/user/src/hooks/socket/useChatSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export default function useChatSocket() {
const chatMessage = { content };

socketClient.sendMessages({
destination: CHAT_SOCKET_ENDPOINTS.SUBSCRIBE,
destination: CHAT_SOCKET_ENDPOINTS.PUBLISH_CHAT,
body: chatMessage,
});
} catch (error) {
Expand Down
4 changes: 2 additions & 2 deletions packages/user/src/services/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,14 @@ class SocketManager {

if (this.onReceiveMessage) {
this.socketClient.subscribe({
destination: CHAT_SOCKET_ENDPOINTS.SUBSCRIBE,
destination: CHAT_SOCKET_ENDPOINTS.SUBSCRIBE_CHAT,
callback: this.onReceiveMessage,
});
}

if (this.onReceiveBlock) {
this.socketClient.subscribe({
destination: CHAT_SOCKET_ENDPOINTS.BLOCK,
destination: CHAT_SOCKET_ENDPOINTS.SUBSCRIBE_BLOCK,
callback: this.onReceiveBlock,
});
}
Expand Down