Skip to content

Commit

Permalink
Merge pull request #106 from Hanjuri/feature/#49
Browse files Browse the repository at this point in the history
feat:로그인 수정최종 및 채팅방 연결
  • Loading branch information
Hanjuri authored Sep 10, 2024
2 parents 9801c17 + 9def0b5 commit 8674e37
Show file tree
Hide file tree
Showing 11 changed files with 145 additions and 128 deletions.
16 changes: 5 additions & 11 deletions eslint.config.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import reactRefresh from "eslint-plugin-react-refresh";
import prettier from "eslint-config-prettier";
import prettierPlugin from "eslint-plugin-prettier";
import globals from "globals";
import react from "@vitejs/plugin-react";
import reactHooks from "@eslint/js";
import js from "@eslint/js";
import reactPlugin from "eslint-plugin-react";
import reactHooksPlugin from "eslint-plugin-react-hooks";

export default [
{
Expand All @@ -21,8 +19,8 @@ export default [
},
settings: { react: { version: "18.3" } },
plugins: {
react,
"react-hooks": reactHooks,
react: reactPlugin,
"react-hooks": reactHooksPlugin,
"react-refresh": reactRefresh,
prettier: prettierPlugin,
},
Expand All @@ -32,10 +30,6 @@ export default [
"plugin:prettier/recommended",
],
rules: {
...js.configs.recommended.rules,
...react.configs.recommended.rules,
...react.configs["jsx-runtime"].rules,
...reactHooks.configs.recommended.rules,
"react/jsx-no-target-blank": "off",
"react-refresh/only-export-components": [
"warn",
Expand All @@ -44,4 +38,4 @@ export default [
"prettier/prettier": "error",
},
},
];
];
9 changes: 5 additions & 4 deletions src/api/ChatListCall.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import axios from "axios";
import { instance } from "./instance.js";

export const getChatList = async (username = "pjh1") => {
export const getChatList = async (username) => {
try {
const response = await instance.get("/chat/rooms");
console.log(response);
const response = await instance.get(`/chat/rooms?username=${username}`);
console.log('apicall',username, response);
return response;
} catch (error) {
console.error("Error fetching chat list!:", error.message);
throw error;
}
};
};
2 changes: 1 addition & 1 deletion src/api/ChatMessageCall.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const getChatMessages = async (roomUUID, page = 0, size = 10) => {
size // 페이지 당 메시지 수
}
});
return response.data;
return response;
} catch (error) {
console.error("채팅방 메세지 불러오기 실패:", error.message);
throw error;
Expand Down
14 changes: 7 additions & 7 deletions src/pages/chat/ChatMain.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,16 @@ import dummyChatList from "./dummyChatData/dummyChatList";
function ChatMain() {
const [chatList, setChatList] = useState([])
const [selectedChatRoom, setSelectedChatRoom] = useState(null);
const nowUser = 'pjh2';
const nowUser = 'user1';



useEffect(() => {
const fetchChatList = async () => {
try {
const response = await getChatList(nowUser); // 사용자 이름을 동적으로 설정 가능
setChatList(response);
console.log('채팅방리스트 불러오기 성공', response);
const response = await getChatList(nowUser);
setChatList(response.data.data);
console.log('채팅방리스트 불러오기 성공', response.data.data);
} catch (error) {
console.error("채팅방리스트 불러오기 실패", error);
}
Expand All @@ -40,7 +40,7 @@ function ChatMain() {
</styles.TitleWrapper>
<styles.ChatWrapper>
<styles.LeftWrapper>
{Array.isArray(dummyChatList)&&dummyChatList.map((eachChat, id) => (
{Array.isArray(chatList)&&chatList.map((eachChat, id) => (
<styles.ChatListButton
key={eachChat.chatRoomUUID}
onClick={(e)=>{
Expand All @@ -49,8 +49,8 @@ function ChatMain() {
<ChatList
uuid={eachChat.chatRoomUUID}
name={eachChat.chatRoomName}
content={eachChat.chatContent}
time={eachChat.time}
content={"카부카부"}
time={"2020.08.09"}
alramcount={3}></ChatList>
</styles.ChatListButton>

Expand Down
175 changes: 86 additions & 89 deletions src/pages/chat/ChatRoom.jsx
Original file line number Diff line number Diff line change
@@ -1,79 +1,81 @@
import React, { useEffect, useState } from "react";
import * as Stomp from 'stompjs';
import SockJS from "sockjs-client";
import * as Stomp from "stompjs";
import * as styles from "./styled/ChatRoom.styled";
import Text from "../../components/Common/Text";
import ChatMessage from "./ChatMessage.jsx";
import { getChatMessages } from "../../api/ChatMessageCall.js";
import dummyChatMessages from "./dummyChatData/dummyChatMessages1";

const ChatRoom = (props) => {
const { uuid, name } = props;
const [messages, setMessages] = useState([]);
const [message, setMessage] = useState("");
const [stompClient, setStompClient] = useState(null);

const currentUsername = '홍창기'; // 현재 사용자를 pjh2로 가정

const roomId = props.uuid;

// 채팅방 메세지 데이터 가져오기
useEffect(() => {
const fetchMessages = async () => {
try {
const response = await getChatMessages(uuid, 0, 10);
// 메시지 데이터에 isCurrentUser 추가
const modifiedMessages = Array.isArray(response.data)
? response.data.map((msg) => ({
...msg,
isCurrentUser: msg.username === currentUsername,
}))
: [];
setMessages(modifiedMessages);
console.log("채팅방 메세지 데이터:", modifiedMessages, response);
} catch (error) {
console.error("Failed to fetch chat messages", error);
}
};
fetchMessages();
}, [roomId]);

// 실시간 웹소켓 연결 및 메세지 보내기
useEffect(() => {
const newSocket = io(import.meta.env.VITE_BASE_URL, {
path: "/chat/ws", // 서버에서 설정한 경로로 수정
query: { roomId: uuid },
});

setSocket(newSocket);

newSocket.on("connect", () => {
console.log("WebSocket에 연결되었습니다!");
});

newSocket.on("message", (chatMessage) => {
console.log("WebSocket 메세지 수신", chatMessage);
setMessages((prevMessages) => [
...prevMessages,
{
id: chatMessage.id,
user: chatMessage.username,
message: chatMessage.message,
time: new Date().toLocaleTimeString(),
isCurrentUser: chatMessage.username === currentUsername,
},
]);
});
const currentUsername = '홍창기'; // 현재 사용자 설정
const roomId = uuid;
const [stompClient, setStompClient] = useState(null); // STOMP 클라이언트 객체 저장

// 채팅방 메시지 데이터 가져오기
useEffect(() => {
const fetchMessages = async () => {
try {
const response = await getChatMessages(uuid, 0, 10);
const dataList = response.data.data;
const modifiedMessages = Array.isArray(dataList)
? dataList.map((msg) => ({
...msg,
isCurrentUser: msg.username === currentUsername,
}))
: [];
modifiedMessages.sort((a, b) => new Date(a.sendAt) - new Date(b.sendAt));
setMessages(modifiedMessages);
console.log("채팅방 메시지 데이터:", modifiedMessages);
} catch (error) {
console.error("Failed to fetch chat messages", error);
}
};
fetchMessages();
}, [uuid]);

// WebSocket 연결 및 메시지 구독
useEffect(() => {
const socket = new SockJS(`${import.meta.env.VITE_BASE_URL}chat/ws`);
const stompClient = Stomp.over(socket);

stompClient.connect({}, () => {
console.log("STOMP WebSocket에 연결되었습니다!");

// 구독 설정 (서버에서 채팅방 메시지를 수신)
stompClient.subscribe(`/sub/chat/room/${uuid}`, (message) => {
const chatMessage = JSON.parse(message.body);
console.log("WebSocket 메시지 수신", chatMessage);

// 수신된 메시지를 메시지 리스트에 추가
setMessages((prevMessages) => [
...prevMessages,
{
id: chatMessage.id,
username: chatMessage.username,
message: chatMessage.message,
time: new Date().toLocaleTimeString(),
isCurrentUser: chatMessage.username === currentUsername,
},
]);
});
});

// STOMP 클라이언트 객체를 저장
setStompClient(stompClient);

// 연결 해제 시 클린업
return () => {
if (client) {
client.disconnect(() => {
console.log("WebSocket 연결 해제 되었습니다!");
});
if (stompClient) {
stompClient.disconnect();
console.log("STOMP WebSocket 연결 해제 되었습니다!");
}
};
}, [uuid]); // uuid 변경될 때마다 재연결
}, [uuid]);

// 메시지 전송
const sendMessage = () => {
if (message.trim() === "" || !stompClient || !uuid) {
return;
Expand All @@ -86,32 +88,24 @@ const ChatRoom = (props) => {
message: message,
};

// 서버로 메시지 발행 (전송)
stompClient.send("/pub/messages", {}, JSON.stringify(chatMessage));

setMessages(prevMessages => {
if (Array.isArray(prevMessages)) {
return [
...prevMessages,
{
id: Date.now(), // 임시로 고유 ID를 부여
user: chatMessage.username,
text: chatMessage.message,
time: new Date().toLocaleTimeString(),
isCurrentUser: true, // 현재 사용자가 보낸 메시지이므로 true
}
];
} else {
return [{
id: Date.now(),
user: chatMessage.username,
text: chatMessage.message,
time: new Date().toLocaleTimeString(),
isCurrentUser: true,
}];
}
});

setMessage("");
// 클라이언트에서 즉시 메시지 추가
setMessages((prevMessages) => [
...prevMessages,
{
id: Date.now(),
username: chatMessage.username,
message: chatMessage.message,
time: new Date().toLocaleTimeString(),
isCurrentUser: true,
},
]);

console.log("전송된 메시지:", chatMessage);

setMessage(""); // 입력창 초기화
};

return (
Expand All @@ -122,14 +116,17 @@ const ChatRoom = (props) => {
fontFamily="KakaoBold"
fontSize={45}
color="#000"
>{name}</Text>
>
{name}
</Text>
</styles.NameWrapper>
<styles.ChatRoomWrapper>
{Array.isArray(dummyChatMessages) && dummyChatMessages.map((each, id) => (
{Array.isArray(messages) && messages.map((each, id) => (
<ChatMessage
key={id}
name={each.username}
message={each.message}
time={each.time}
time={each.sendAt}
isCurrentUser={each.isCurrentUser}
/>
))}
Expand All @@ -142,12 +139,12 @@ const ChatRoom = (props) => {
value={message}
onChange={(e) => setMessage(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && sendMessage()}
></styles.Input>
/>
</styles.InputWrapper>
<styles.SendButton onClick={sendMessage}>{'>'}</styles.SendButton>
</styles.BottomWrapper>
</styles.TotalWrapper>
);
};

export default ChatRoom;
export default ChatRoom;
3 changes: 2 additions & 1 deletion src/pages/chat/styled/ChatMessage.styled.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@ export const lineTotalWrapper = styled.div`
flex-direction: row;
margin-top: 6px;
margin-left: 15px;
background-color: yellow;
`;
export const lineTotalWrapper2 = styled.div`
height: auto;
display: flex;
flex-direction: row;
justify-content: flex-end;
margin-top: 6px;
margin-top: 10px;
margin-right: 15px;
`;
export const profileWrapper = styled.div`
Expand Down
Loading

0 comments on commit 8674e37

Please sign in to comment.