Skip to content

Commit

Permalink
✨ feat : 채팅 룸 분리
Browse files Browse the repository at this point in the history
  • Loading branch information
LikeFireAndSky committed Jan 19, 2024
1 parent b52f9bd commit 5cf039a
Show file tree
Hide file tree
Showing 8 changed files with 170 additions and 12 deletions.
7 changes: 5 additions & 2 deletions app/stomp/sock/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
import React, { useState, useEffect } from 'react';
import SockJS from 'sockjs-client';
import { CompatClient, Stomp } from '@stomp/stompjs';
import { useRecoilState } from 'recoil';
import { chatContentAtom } from '@/atoms/chat/chatContentAtom';

// test 완료되면 지우도록 하겠습니다

const ROOMID = '02d6b08d-60f8-4c21-b5b2-0ba7af752e29';

type Content = {
export type ChatContentType = {
type: 'ENTER' | 'TALK' | 'LEAVE';
message: string;
sender: string;
Expand All @@ -17,7 +19,8 @@ type Content = {
};

const StompPage = () => {
const [message, setMessage] = useState<Content[]>([]);
const [message, setMessage] =
useRecoilState<ChatContentType[]>(chatContentAtom);
const [ws, setWs] = useState<CompatClient | null>(null);

const connect = () => {
Expand Down
38 changes: 31 additions & 7 deletions app/talk/FindRoomInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ import axios from 'axios';
import { useCookies } from 'react-cookie';
import { useQuery } from '@tanstack/react-query';
import BottomSheets from '@/components/common/bottomSheets';
import Image from 'next/image';

const fetchRoomInfo = async (token: string, roomNumber: string) => {
const data = await axios.get(
`https://catchroom.xyz/v1/chat/find?id=${roomNumber}`,
`https://catchroom.xyz/v1/chat/room?roomId=${roomNumber}`,
{
headers: {
'Content-Type': 'application/json',
Expand All @@ -18,29 +19,52 @@ const fetchRoomInfo = async (token: string, roomNumber: string) => {
);

const result = await data.data;
return result;
return result.data;
};

const FindRoomInfo = ({ roomNumber }: { roomNumber: string }) => {
const [cookies] = useCookies();
const { data, isLoading, isError, error } = useQuery({
queryKey: ['roomInfo'],
console.log(cookies.accessToken, 'accessToken');
const { data, isLoading, isError } = useQuery({
queryKey: ['roomInfo', roomNumber],
queryFn: () => fetchRoomInfo(cookies.accessToken, roomNumber),
retryOnMount: true,
});

const LoadingComponent = isLoading && <div>로딩중...</div>;
const ErrorComponent = isError && <div>에러가 발생했습니다.</div>;

console.log(data, 'data');
console.log(error, 'error');

return (
<div>
<BottomSheets title="채팅방 정보">
{LoadingComponent}
{ErrorComponent}
<div>정보 보기</div>
{data && (
<div className="w-full relative flex gap-3">
<div className="w-20 h-20 relative rounded-xl overflow-hidden">
<Image
src={data.productImage}
fill
sizes="(max-width: 640px) 70vw, 100vw"
alt="상품이미지"
/>
</div>
<div className="grow ">
<p>{data.partnerNickName}님과의 채팅방✨</p>
<div className="w-full flex flex-col">
<p className="w-full text-h4 font-bold">{data.productName}</p>
<div className="w-full flex justify-between gap-1">
<div className="flex">
<p>판매자 ID : {data.sellerId}</p>
<p>구매자 ID : {data.buyerId}</p>
</div>
<p className="text-t2">가격 : {data.price}</p>
</div>
</div>
</div>
</div>
)}
</BottomSheets>
</div>
);
Expand Down
104 changes: 104 additions & 0 deletions app/talk/[room]/Room.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
'use client';

import React, { useState, useEffect } from 'react';
import SockJS from 'sockjs-client';
import { CompatClient, Stomp } from '@stomp/stompjs';

// test 완료되면 지우도록 하겠습니다

const ROOMID = '02d6b08d-60f8-4c21-b5b2-0ba7af752e29';

type Content = {
type: 'ENTER' | 'TALK' | 'LEAVE';
message: string;
sender: string;
roomId: string;
userId: string;
};

const StompPage = () => {
const [message, setMessage] = useState<Content[]>([]);
const [ws, setWs] = useState<CompatClient | null>(null);

const connect = () => {
const sockjs = new SockJS('http://13.124.240.142:8080/ws-stomp');
const ws = Stomp.over(sockjs);

setWs(ws);

// eslint-disable-next-line
ws.connect({}, () => {
ws.subscribe(`/sub/chat/room/${ROOMID}`, (message) => {
const recv = JSON.parse(message.body);
setMessage((prev) => [...prev, recv]);
});

ws.publish({
destination: `/pub/chat/message`,
body: JSON.stringify({
roomId: ROOMID,
sender: '지운',
type: 'ENTER',
userId: 'user2',
message: '소켓 연결 성공!',
}),
});
});
};

useEffect(() => {
connect();
return () => {
ws?.disconnect();
};
// eslint-disable-next-line
}, []);

const sendMessage = () => {
if (!ws) return;
ws.publish({
destination: `/pub/chat/message`,
body: JSON.stringify({
roomId: ROOMID,
sender: '지운',
type: 'TALK',
userId: 'user2',
message: '안녕하세용',
}),
});
};

const sendMessage2 = () => {
if (!ws) return;
ws.publish({
destination: `/pub/chat/message`,
body: JSON.stringify({
roomId: ROOMID,
sender: '민섭',
type: 'TALK',
userId: 'user1',
message: '안녕하세용',
}),
});
};

return (
<>
{message.map((item, index) => (
<div key={index}>
{item.sender} : {item.message}
</div>
))}
<div className="w-full flex justify-between">
<button className="bg-mint" onClick={sendMessage}>
채팅 보내기
</button>
<button className="bg-mint" onClick={sendMessage2}>
민섭 채팅 보내기
</button>
</div>
</>
);
};

export default StompPage;
14 changes: 14 additions & 0 deletions app/talk/[room]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import StompPage from '@/app/stomp/sock/page';
import React from 'react';

const page = ({ params }: { params: { room: string } }) => {
const { room } = params;
return (
<div>
page {room}
<StompPage />
</div>
);
};

export default page;
13 changes: 13 additions & 0 deletions atoms/chat/chatContentAtom.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { ChatContentType } from '@/app/stomp/sock/page';
import { CompatClient } from '@stomp/stompjs';
import { atom } from 'recoil';

export const chatContentAtom = atom<ChatContentType[]>({
key: 'chatContentAtom',
default: [],
});

export const wsAtom = atom<CompatClient | null>({
key: 'wsAtom',
default: null,
});
2 changes: 1 addition & 1 deletion next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const nextConfig = {
return config;
},
images: {
domains: ['res.cloudinary.com'],
domains: ['res.cloudinary.com', 'yaimg.yanolja.com'],
},
async redirects() {
return [
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev --experimental-https",
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,6 @@
},
"types": ["node", "jest", "@testing-library/jest-dom"],
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", "jest.setup.ts", "jest.config.js"],
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", "jest.setup.ts", "jest.config.js", "app/talk/[room]"],
"exclude": ["node_modules"]
}

0 comments on commit 5cf039a

Please sign in to comment.