Skip to content

Commit d6360d2

Browse files
authored
Merge pull request #200 from prgrms-web-devcourse-final-project/feat/159-chat-request-and-cancel
[feat] 채팅 기능 구현 중, youtube player 수정
2 parents c342e86 + 7b70442 commit d6360d2

File tree

15 files changed

+278
-213
lines changed

15 files changed

+278
-213
lines changed

src/apis/axios.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,27 @@ export const axiosInstance = axios.create({
1111
baseURL: API_BASE_URL,
1212
withCredentials: true, // RT 자동 포함
1313
});
14+
export const axiosChatInstance = axios.create({
15+
baseURL: '/chatapi',
16+
});
17+
18+
// 요청 인터셉터
19+
axiosChatInstance.interceptors.request.use(
20+
async (config) => {
21+
// 토큰 가져오기
22+
const token = useAuthStore.getState().accessToken;
23+
// 토큰이 있으면 요청 헤더에 추가
24+
if (token) {
25+
config.headers.Authorization = `Bearer ${token}`;
26+
// console.log('요청 헤더에 Authorization 추가됨:', config.headers);
27+
}
28+
return config;
29+
},
30+
(error) => {
31+
console.log('요청 인터셉터 에러', error);
32+
Promise.reject(error);
33+
},
34+
);
1435

1536
// 요청 인터셉터
1637
axiosInstance.interceptors.request.use(

src/apis/chat.ts

Lines changed: 16 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,39 @@
1-
import { axiosInstance } from './axios';
1+
import { axiosChatInstance, axiosInstance } from './axios';
22

33
//채팅 목록 불러오기(지난 대화 기록 페이지)
44
export const loadChatList = async () => {
55
const { data } = await axiosInstance.get(`/chat/room-list`);
66
return data;
77
};
8-
9-
//채팅방 기록 불러오기(시간 끝난 채팅방 채팅 기록)
10-
//수신,송신자 정보 / messageList 정보
11-
export const loadChatMessages = async (roomId: number) => {
12-
const { data } = await axiosInstance.get(`/chat/messages/${roomId}`);
13-
return data;
14-
};
158
//채팅 요청
169
export const requestChat = async (emotionRecordId: number) => {
17-
const { data } = await axiosInstance.post(`/chat/request`, emotionRecordId, {
18-
headers: {
19-
'Content-Type': 'application/json',
20-
},
21-
});
10+
const { data } = await axiosInstance.post(`/chat/request?recordId=${emotionRecordId}`, {});
2211
return data;
2312
};
2413
//채팅 요청 취소
2514
export const cancelChatRequest = async (emotionRecordId: number) => {
26-
const { data } = await axiosInstance.delete(`/chat/request`, {
27-
headers: {
28-
'Content-Type': 'application/json',
29-
},
30-
data: JSON.stringify(emotionRecordId),
31-
});
15+
const { data } = await axiosInstance.delete(`/chat/request?recordId=${emotionRecordId}`, {});
3216
return data;
3317
};
3418
//채팅방 생성
3519
export const createChatroom = async (emotionRecordId: number) => {
36-
const { data } = await axiosInstance.post(
37-
`/chat/create?recordId=${emotionRecordId}`,
38-
{},
39-
);
20+
const { data } = await axiosInstance.post(`/chat/create?recordId=${emotionRecordId}`, {});
4021
return data;
4122
};
4223
//채팅방 닫기
4324
export const closeChatroom = async (chatRoomId: number) => {
4425
const { data } = await axiosInstance.post(`/chat/close?chatRoomId=${chatRoomId}`, {});
4526
return data;
4627
};
28+
//채팅방 기록 불러오기
29+
export const loadChatHistory = async (chatRoomId: number) => {
30+
const { data } = await axiosChatInstance.get(`/chat/history/${chatRoomId}`);
31+
return data;
32+
};
33+
//채팅방 상세 정보
34+
export const loadChatRoomDetail = async (chatRoomId: number) => {
35+
const { data } = await axiosInstance.get(`/chat/room/detail`, {
36+
params: { chatRoomId: chatRoomId },
37+
});
38+
return data;
39+
};

src/components/ChatConnectLoadingSheet.tsx

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ dayjs.extend(duration);
1313
export default function ChatConnectLoadingSheet() {
1414
const navigate = useNavigate();
1515

16-
const { currentRecord, setCurrentRecord, closeAllSheets, closeSheet } = useSheetStore();
16+
const { currentRecord, closeAllSheets, closeSheet } = useSheetStore();
1717

1818
const [timeLeft, setTimeLeft] = useState(60);
1919

@@ -72,21 +72,17 @@ export default function ChatConnectLoadingSheet() {
7272
//채팅방 생성 (요청 받는 사람 입장에서 생성?)
7373
//sse로 받은 recordId로 채팅방 생성
7474
//sse로 받은 상대 정보로 '보내는 사람' 바꾸기
75-
//생성 시 currentRecord 에 id 저장
7675
const createChat = async () => {
7776
try {
78-
const data = await createChatroom(10);
77+
//1 = recordId
78+
const data = await createChatroom(1);
7979
console.log(data);
80-
// const chatRoomId = data.data.chatRoomId; 배포할때 잠시 주석처리하겠습니다
81-
82-
if (data.code === 200) {
83-
//임시
84-
setCurrentRecord({ recordId: 10 });
85-
//
86-
navigate(`/chatroom/10`);
87-
closeAllSheets();
88-
}
80+
const chatRoomId = data.data.chatRoomId;
81+
82+
//200
8983
//409 이면 이미 채팅방 있음 => 기존 채팅방으로
84+
navigate(`/chatroom/${chatRoomId}`);
85+
closeAllSheets();
9086
} catch (error) {
9187
console.log(error);
9288
}
@@ -100,6 +96,7 @@ export default function ChatConnectLoadingSheet() {
10096
};
10197

10298
//채팅 신청한 사람은 상대가 수락했다는 sse 받으면 closeAllSheet, chatroom으로 이동
99+
//sse로 채팅방 번호 받기
103100

104101
if (connetFail) {
105102
return (

src/components/MusicCard.tsx

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,14 +54,15 @@ export default function MusicCard({
5454
try {
5555
const currentMusicId = spotifyId;
5656
const res = await getSpotifyVideoId(currentMusicId);
57-
const savedVideoId = res.data.videoId;
57+
const savedVideoId = res.data;
58+
console.log(savedVideoId)
5859
setCurrentVideoId(savedVideoId);
5960
} catch (error) {
6061
console.log(error);
6162
}
6263
};
6364
getVideoId();
64-
}, []);
65+
}, [spotifyId]);
6566

6667
const { setVideoId, players, setIsPlaying } = useYouTubeStore();
6768

src/components/modalSheet/CardDetailModal.tsx

Lines changed: 16 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -30,51 +30,40 @@ function CardDetailModal({ isChatting, recordId, handleDelete, handleEdit }: Car
3030
const [currentVideoId, setCurrentVideoId] = useState<string | null>(null);
3131

3232
useEffect(() => {
33+
if (!data?.data?.spotifyMusic) return; // 데이터가 없으면 실행하지 않음
34+
35+
setCurrentRecord(data.data);
36+
3337
const getVideoId = async () => {
3438
if (!data?.data?.spotifyMusic) return; // 데이터가 없으면 실행하지 않음
35-
39+
//videoId 없으면 검색
3640
try {
3741
const currentMusicId = data.data.spotifyMusic.spotifyId;
3842
const res = await getSpotifyVideoId(currentMusicId);
39-
const savedVideoId = res.data.videoId;
43+
const savedVideoId = res.data;
4044
setCurrentVideoId(savedVideoId);
4145
} catch (error) {
4246
console.log(error);
4347
}
4448
};
45-
getVideoId();
46-
}, []);
4749

48-
// videoId가 변경될 때마다 zustand store의 videoId를 업데이트
49-
useEffect(() => {
50-
if (currentVideoId) {
51-
setVideoId('2', currentVideoId); // YouTube store의 videoId를 업데이트
50+
if (data.data.spotifyMusic.videoId) {
51+
setCurrentVideoId(data.data.spotifyMusic.videoId);
52+
} else {
53+
getVideoId();
5254
}
53-
}, [currentVideoId]);
54-
55-
useEffect(() => {
56-
if (!data?.data?.spotifyMusic) return; // 데이터가 없으면 실행하지 않음
57-
console.log(data?.data);
58-
59-
setCurrentRecord(data.data);
6055

6156
return () => {
6257
setCurrentRecord(null);
6358
};
6459
}, [data]);
6560

66-
// //sheet open 시 스크롤 제거
67-
// useEffect(() => {
68-
// if (isCardSheetOpen) {
69-
// document.body.style.overflow = 'hidden'; // 스크롤 막기
70-
// } else {
71-
// document.body.style.overflow = 'auto'; // 스크롤 복원
72-
// }
73-
74-
// return () => {
75-
// document.body.style.overflow = 'auto';
76-
// };
77-
// }, [isCardSheetOpen]);
61+
// videoId가 변경될 때마다 zustand store의 videoId를 업데이트
62+
useEffect(() => {
63+
if (currentVideoId) {
64+
setVideoId('3', currentVideoId); // YouTube store의 videoId를 업데이트
65+
}
66+
}, [currentVideoId]);
7867

7968
if (!isCardSheetOpen) {
8069
return null;

src/components/modalSheet/ChatActionButtons.tsx

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -47,21 +47,20 @@ function ChatActionButtons({
4747
try {
4848
const data = await requestChat(recordId);
4949
console.log(data);
50-
if (data.code === 200) {
51-
console.log('채팅 요청 성공');
5250

53-
openSheet('isChatLoadingSheetOpen');
54-
} else {
55-
console.log('채팅 요청 실패');
56-
openModal({
57-
title: '잠시 후 다시 시도해 주세요',
58-
onConfirm: () => {
59-
closeModal();
60-
},
61-
});
62-
}
51+
//200
52+
console.log('채팅 요청 성공');
53+
openSheet('isChatLoadingSheetOpen');
54+
//409면 데이터로 chatroomid 추가로 옴
55+
//리시버 false
6356
} catch (error) {
6457
console.log(error);
58+
openModal({
59+
title: '잠시 후 다시 시도해 주세요',
60+
onConfirm: () => {
61+
closeModal();
62+
},
63+
});
6564
}
6665
};
6766

src/layouts/Layout.tsx

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ import HeaderWithBack from '@/layouts/header/HeaderWithBack';
55
import HeaderChat from '@/layouts/header/HeaderChat';
66
import { twMerge } from 'tailwind-merge';
77
import PostButton from '@/components/PostButton';
8-
import { useRef } from 'react';
8+
import { useEffect, useRef } from 'react';
9+
import { useScrollStore } from '@/store/scrollStore';
910

1011
function Layout() {
1112
const location = useLocation(); // 현재 URL 가져오기
@@ -49,7 +50,11 @@ function Layout() {
4950
const hasPostButton = location.pathname === '/home' || location.pathname === '/mypage';
5051

5152
//헤더 클릭 시 스크롤
52-
const scrollContainerRef = useRef<HTMLDivElement>(null); // 스크롤 컨테이너 참조
53+
const { setScrollContainerRefCurrent } = useScrollStore();
54+
const scrollContainerRef = useRef<HTMLDivElement | null>(null); // 스크롤 컨테이너 참조
55+
useEffect(() => {
56+
if (scrollContainerRef.current) setScrollContainerRefCurrent(scrollContainerRef.current);
57+
}, [scrollContainerRef]);
5358

5459
const handleScrollToTop = () => {
5560
if (scrollContainerRef.current) {

src/layouts/header/HeaderChat.tsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,8 +74,10 @@ function HeaderChat({ showLogo = false, showNickname = false }: HeaderChatProps)
7474
}
7575
console.log('확인');
7676
console.log(chatRoomId);
77-
const data = await closeChatroom(Number(10));
77+
const data = await closeChatroom(Number(chatRoomId));
7878
console.log(data);
79+
//+ 웹소켓 연결 끊기
80+
//+ 로딩
7981

8082
navigate('/home');
8183
closeModal();

src/pages/chat/Chat.tsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ export default function Chat({}) {
99
useEffect(() => {
1010
const getChatList = async () => {
1111
const { data } = await loadChatList();
12+
console.log(data);
1213
setChatList(data);
1314
};
1415
getChatList();
@@ -24,7 +25,7 @@ export default function Chat({}) {
2425
return (
2526
<div className="w-full mt-[12px] mb-[58px] flex flex-col gap-4">
2627
{chatList.map((item) => (
27-
<ChatHistoryCard item={item} key={item.chatroom_id} />
28+
<ChatHistoryCard item={item} key={item.chatRoomId} />
2829
))}
2930
</div>
3031
);

0 commit comments

Comments
 (0)