Skip to content

Commit

Permalink
[feat]: 상대 유저가 채팅방에 있는지 확인 후 알림 전송 여부를 결정하는 기능 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
Gseungmin committed Aug 22, 2023
1 parent 41c91c3 commit a0b58ed
Showing 1 changed file with 14 additions and 7 deletions.
21 changes: 14 additions & 7 deletions socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ module.exports = (io) => {
//사용자가 특정 채팅방에 참여하려고할때 클라이언트에서 발생함, 이때 roomId와 userId를 매개변수로 전달
socket.on('joinRoom', (roomId, userId) => {
socket.join(roomId); //소켓을 roomId에 지정된 방에 조인
socket.userId = userId; //사용자 ID를 소켓에 연결
console.log(`User ${userId} joined room ${roomId}`);
});

Expand Down Expand Up @@ -96,20 +97,26 @@ module.exports = (io) => {
// 메시지 저장
await newMessage.save(); //저장 메시지 생성

const { otherFcm } = await getFcm(otherId); //fcm 토큰 정보 받아오기
const socketsInRoom = await io.in(roomId).fetchSockets(); //모든 소켓의 회원 ID 목록을 가지고 옴
const isInRoom = socketsInRoom.some(s => s.userId === otherId); // 해당 방에 otherId가 있는지 확인

//만약 방에 있다면, 알림 전송
if (isInRoom) {
const { otherFcm } = await getFcm(otherId); //fcm 토큰 정보 받아오기

if (otherFcm) {
await sendNotificationToToken(otherFcm, userId, newMessage.content);
} else {
console.error('No valid FCM token available');
}
}

// 같은 채팅방에 있는 모든 클라이언트에게 메시지 전송
io.to(roomId).emit('message', {
content: newMessage.content,
username: newMessage.username,
time: newMessage.time,
});

if (otherFcm) {
await sendNotificationToToken(otherFcm, userId, newMessage.content);
} else {
console.error('No valid FCM token available');
}
});

// 클라이언트가 방을 나갈 때 실행할 이벤트 핸들러
Expand Down

0 comments on commit a0b58ed

Please sign in to comment.