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] websocket 백엔드 변경 사항 반영 #207

Merged
merged 8 commits into from
Apr 6, 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
51 changes: 36 additions & 15 deletions src/api/get.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
import { getInstance, getPublicInstance } from './axios';
//admin

/**
* Admin Controller
*/
export const getAdminsUnpaidConsults = async () =>
await getInstance('/admins/unpaid-consults');
export const getAdminsPedningProfilse = async () =>
await getInstance('/admins/pending-profiles');
export const getAdminsRefundWaiting = async () =>
await getInstance('/admins/refund-waiting');
// //밑에 두개 지우기
// export const getChats = async (params: any) =>
// await getInstance('/chats', params);
// export const getLetters = async (params: any) =>
// await getInstance('/letters', params);

// 판매자 사이드 letter list
export const getConselorLetters = async (params: any) =>
await getInstance('/letters/counselors', params);

//Chat Controller
/**
* Chat Controller
*/
//채팅 목록 반환
export const getChatsCustomers = async (params: any) =>
await getInstance('/chats/customers', params);
Expand All @@ -32,14 +32,19 @@ export const getChatMessagesCounselors = async (chatId: string, params: any) =>

export const getChatsMinder = async (params: any) =>
await getInstance('/chats/counselors', params);
//Consult Controller

/**
* Consult Controller
*/
export const getConsultsCustomers = async () =>
await getPublicInstance('/consults/customers');

export const getConsultsMinder = async () =>
await getPublicInstance('/consults/counselors');

//Letter Controller
/**
* Letter Controller
*/
//편지 목록 반환
export const getLettersCustomers = async (params: any) =>
await getInstance('/letters/customers', params);
Expand All @@ -63,11 +68,16 @@ export const getLetterDeadline = async (letterId: string | undefined) =>
export const getLettersNickname = async (letterId: string | undefined) =>
await getInstance(`/letters/nickname/${letterId}`);

//Customer Controller
/**
* Customer Controller
*/
export const getCustomers = async () => await getInstance('customers');
export const getCustomersNickname = async () =>
await getPublicInstance('/customers/nickname');
//LetterMessage Controller

/**
* LetterMessage Controller
*/
export const getLetterMessages = async (
params: any,
letterId: string | undefined,
Expand All @@ -82,7 +92,10 @@ export const getReviewsCustomer = async (params: any) =>
export const getReviewsAll = async (counselorId: number, params: any) =>
await getPublicInstance(`/reviews/all/${counselorId}`, params);

// Conuselor Controller
/**
* Counselor Controller
*/
export const getCounselors = async () => await getInstance('counselors');
export const getMyInfo = async () => await getInstance('counselors/my-info');
export const getProfiles = async () => await getInstance('counselors/profiles');
export const getIsPassQuiz = async () => await getInstance('counselors/quiz');
Expand All @@ -93,12 +106,18 @@ export const getCounselorConsults = async (
//마인더 프로필 페이지 마인더 프로필 조회
export const getCounselorsAll = async (counselorId: string | undefined) =>
await getPublicInstance(`/counselors/all/${counselorId}`);
// SearchWord Controller

/**
* SearchWord Controller
*/
export const getSearchWords = async () =>
await getPublicInstance('/searchWords');
export const getCounselorsChats = async (chatId: string, params: any) =>
await getInstance(`/counselors/chats/${chatId}`, params);
//Payment Controller

/**
* Payment Controller
*/
export const getPaymentsCustomers = async (params: any) =>
await getInstance('/payments/customers', params);

Expand All @@ -107,8 +126,10 @@ export const getPaymentsMinder = async (params: any) =>

export const getPaymentsHome = async () =>
await getInstance('/payments/counselors/home');
//Review Controller

/**
* Review Controller
*/
export const getMinderReviews = async (params: any) =>
await getInstance('/reviews/counselors', params);
export const getMinderReviewsHome = async () =>
Expand Down
191 changes: 110 additions & 81 deletions src/components/Buyer/BuyerConsult/BuyerChatSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,31 @@ import styled from 'styled-components';
import { ConsultCard } from 'components/Buyer/Common/ConsultCard';
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { consultApiObject } from 'pages/Buyer/BuyerConsult';
import { getChatsCustomers } from 'api/get';
import { getChatsCustomers, getCustomers } from 'api/get';
import { useStompContext } from 'contexts/StompContext';
import { LoadingSpinner } from 'utils/LoadingSpinner';
import { Heading } from 'styles/font';
import { ReactComponent as Empty } from 'assets/icons/graphic-noting.svg';
import { convertChatListDate } from 'utils/convertDate';

//
//
//

interface BuyerChatSectionProps {
sortType: number;
isChecked: boolean;
}

//
//
//

export const BuyerChatSection = ({
sortType,
isChecked,
}: BuyerChatSectionProps) => {
const [cardData, setCardData] = useState<consultApiObject[]>([]); //card에 넘길 데이터

const [isLoading, setIsLoading] = useState<boolean>(true);

const roomIdsRef = useRef<number[]>([]); //unmout 시 unsubscibe를 위함
Expand All @@ -30,7 +38,10 @@ export const BuyerChatSection = ({
*/
const cardDataRef = useRef<consultApiObject[]>([]);
const { stompClient, isConnected } = useStompContext();
//채팅 readId, 가장 최근 unread message, 정렬 업데이트

/**
* 채팅 readId, 가장 최근 unread message, 정렬 업데이트
*/
const updateChatData = (
chatId: number,
content: string,
Expand All @@ -57,85 +68,34 @@ export const BuyerChatSection = ({
}
};

useEffect(() => {
if (!isConnected) {
return;
}

if (stompClient.current) {
stompClient.current.subscribe(
'/queue/chattings/connect/customers/',
(rooms) => {
const response = JSON.parse(rooms.body);
roomIdsRef.current = response.roomIds;

response.roomIds.forEach((chatId: number) => {
//모든 채팅방 subscribe
stompClient.current?.subscribe(
'/queue/chatMessages/customers/' + chatId,
(message) => {
const response = JSON.parse(message.body);
updateChatData(
chatId,
response.content,
convertChatListDate(response.sendTime),
);
},
);
});
if (response.userId !== null) {
userIdRef.current = response.userId;
//채팅방 생성, 종료 readid tab 갱신
stompClient.current?.subscribe(
'/queue/chattings/notifications/customers/' + response.userId,
(message) => {
const notification = JSON.parse(message.body);
if (
notification.chatRoomWebsocketStatus === 'CHAT_ROOM_CREATE'
) {
//add cardData
const addedChatRoomItem: consultApiObject = {
consultStyle: notification.consultStyle,
id: notification.chatId,
latestMessageContent: `${notification.opponentNickname}님께 고민 내용을 남겨 주세요. ${notification.opponentNickname}님이 24시간 이내 답장을 드릴 거예요.`,
latestMessageIsCustomer: null,
latestMessageUpdatedAt: convertChatListDate(
notification.createTime,
),
opponentNickname: notification.opponentNickname,
status: '상담 대기',
unreadMessageCount: 0,
reviewCompleted: null,
consultId: null,
};
//add roomIds for unsubscribe
roomIdsRef.current.unshift(notification.chatId);
/**
* 채팅방 생성 시 chat data add
*/
const addChatData = (notification: any) => {
//add cardData
const addedChatRoomItem: consultApiObject = {
consultStyle: notification.consultStyle,
id: notification.chatId,
latestMessageContent: `${notification.opponentNickname}님께 고민 내용을 남겨 주세요. ${notification.opponentNickname}님이 24시간 이내 답장을 드릴 거예요.`,
latestMessageIsCustomer: null,
latestMessageUpdatedAt: convertChatListDate(notification.createTime),
opponentNickname: notification.opponentNickname,
status: '상담 대기',
unreadMessageCount: 0,
reviewCompleted: null,
consultId: null,
};
//add roomIds for unsubscribe
roomIdsRef.current.unshift(notification.chatId);

cardDataRef.current = [
addedChatRoomItem,
...cardDataRef.current,
];
cardDataRef.current = [addedChatRoomItem, ...cardDataRef.current];

setCardData(cardDataRef.current);
setCardData(cardDataRef.current);
};

//subscribe new chatroom
stompClient.current?.subscribe(
'/queue/chatMessages/customers/' + notification.chatId,
(message) => {
const response = JSON.parse(message.body);
updateChatData(
notification.chatId,
response.content,
convertChatListDate(response.sendTime),
);
},
);
}
},
);
}
},
);
useEffect(() => {
if (!isConnected) {
return;
}

const sendConnectRequest = () => {
Expand All @@ -148,10 +108,79 @@ export const BuyerChatSection = ({
}
};

sendConnectRequest();
const getCustomerUserIdAndSubscribe = async () => {
try {
const response: any = await getCustomers();
userIdRef.current = response.data;
subscribeChatList();
sendConnectRequest();
} catch (e) {
console.error(e);
}
};

const subscribeChatList = () => {
if (stompClient.current) {
// 이거 전에 먼저 userId 를 받고 userId 기준으로 subscribe 한다.
stompClient.current.subscribe(
`/queue/chattings/connect/customers/${userIdRef.current}`,
(rooms) => {
const response = JSON.parse(rooms.body);
roomIdsRef.current = response.roomIds;
response.roomIds.forEach((chatId: number) => {
//모든 채팅방 subscribe
stompClient.current?.subscribe(
'/queue/chatMessages/customers/' + chatId,
(message) => {
const response = JSON.parse(message.body);
updateChatData(
chatId,
response.content,
convertChatListDate(response.sendTime),
);
},
);
});
if (response.userId !== null) {
// userIdRef.current = response.userId;
//채팅방 생성, 종료 readid tab 갱신
stompClient.current?.subscribe(
'/queue/chattings/notifications/customers/' + response.userId,
(message) => {
const notification = JSON.parse(message.body);
if (
notification.chatRoomWebsocketStatus === 'CHAT_ROOM_CREATE'
) {
addChatData(notification);

//subscribe new chatroom
stompClient.current?.subscribe(
'/queue/chatMessages/customers/' + notification.chatId,
(message) => {
const response = JSON.parse(message.body);
updateChatData(
notification.chatId,
response.content,
convertChatListDate(response.sendTime),
);
},
);
}
},
);
}
},
);
}
};

getCustomerUserIdAndSubscribe();

//
//
//

return () => {
console.log('effect callback');
roomIdsRef.current.forEach((value) => {
stompClient.current?.unsubscribe(
'/queue/chatMessages/customers/' + value,
Expand Down
Loading
Loading