Skip to content
Snippets Groups Projects
Commit d7c996e5 authored by 심재엽's avatar 심재엽
Browse files

refactor: 중복 코드 통합, rabbitmq 연결 유지, FcmToken 연관관계 추가 feat: 채팅방 공지사항 기능 추가

parents 95f8e123 45d6eb5e
Branches
No related tags found
2 merge requests!42[#25] 배포코드 master브랜치로 이동,!38refactor: 중복 코드 통합, rabbitmq 연결 유지, FcmToken 연관관계 추가 feat: 채팅방 공지사항 기능 추가
...@@ -91,4 +91,67 @@ exports.updateStatusAndLogId = async (req, res) => { ...@@ -91,4 +91,67 @@ exports.updateStatusAndLogId = async (req, res) => {
console.error('Error updating user status and lastReadLogId:', err); console.error('Error updating user status and lastReadLogId:', err);
res.status(500).json({ error: 'Failed to update user status and lastReadLogId' }); res.status(500).json({ error: 'Failed to update user status and lastReadLogId' });
} }
};
// 공지 등록
exports.addNotice = async (req, res) => {
const { chatRoomId } = req.params;
const { sender, message } = req.body;
try {
const notice = await chatService.addNotice(chatRoomId, sender, message);
res.status(200).json(notice);
} catch (error) {
console.error('Error adding notice:', error.message);
res.status(500).json({ error: 'Failed to add notice' });
}
};
// 최신 공지 조회
exports.getLatestNotice = async (req, res) => {
const { chatRoomId } = req.params;
try {
const latestNotice = await chatService.getLatestNotice(chatRoomId);
if (latestNotice) {
res.status(200).json(latestNotice);
} else {
res.status(404).json({ message: 'No notices found' });
}
} catch (error) {
console.error('Error fetching latest notice:', error.message);
res.status(500).json({ error: 'Failed to fetch latest notice' });
}
};
// 공지 전체 조회
exports.getAllNotices = async (req, res) => {
const { chatRoomId } = req.params;
try {
const notices = await chatService.getAllNotices(chatRoomId);
console.log(`[getAllNotices] Notices for chatRoomId ${chatRoomId}:`, notices); // 로그 추가
res.status(200).json(notices);
} catch (error) {
console.error('Error fetching all notices:', error.message);
res.status(500).json({ error: 'Failed to fetch all notices' });
}
};
// 공지사항 상세 조회
exports.getNoticeById = async (req, res) => {
const { chatRoomId, noticeId } = req.params;
try {
const notice = await chatService.getNoticeById(chatRoomId, noticeId);
if (!notice) {
return res.status(404).json({ error: 'Notice not found' });
}
res.status(200).json(notice);
} catch (error) {
console.error('Error fetching notice by ID:', error.message);
res.status(500).json({ error: 'Failed to fetch notice by ID' });
}
}; };
\ No newline at end of file
...@@ -29,6 +29,9 @@ User.hasMany(MeetingParticipant, { foreignKey: 'user_id', as: 'meetingParticipat ...@@ -29,6 +29,9 @@ User.hasMany(MeetingParticipant, { foreignKey: 'user_id', as: 'meetingParticipat
Schedule.belongsTo(User, { foreignKey: 'user_id', as: 'user' }); Schedule.belongsTo(User, { foreignKey: 'user_id', as: 'user' });
User.hasMany(Schedule, { foreignKey: 'user_id', as: 'schedules' }); User.hasMany(Schedule, { foreignKey: 'user_id', as: 'schedules' });
FcmToken.belongsTo(User, { foreignKey: 'userId', as: 'user' });
User.hasMany(FcmToken, { foreignKey: 'userId', as: 'fcmTokenList' });
Invite.belongsTo(Meeting, { foreignKey: 'meeting_id', as: 'meeting' }); Invite.belongsTo(Meeting, { foreignKey: 'meeting_id', as: 'meeting' });
Invite.belongsTo(User, { foreignKey: 'inviter_id', as: 'inviter' }); // 초대한 사용자 Invite.belongsTo(User, { foreignKey: 'inviter_id', as: 'inviter' }); // 초대한 사용자
Invite.belongsTo(User, { foreignKey: 'invitee_id', as: 'invitee' }); // 초대받은 사용자 Invite.belongsTo(User, { foreignKey: 'invitee_id', as: 'invitee' }); // 초대받은 사용자
......
...@@ -10,5 +10,9 @@ router.get('/unread-messages/:nickname', chatController.getUnreadMessages); ...@@ -10,5 +10,9 @@ router.get('/unread-messages/:nickname', chatController.getUnreadMessages);
router.get('/unread-count/:chatRoomId', chatController.getUnreadCount); router.get('/unread-count/:chatRoomId', chatController.getUnreadCount);
router.post('/update-status-and-logid', chatController.updateStatusAndLogId); router.post('/update-status-and-logid', chatController.updateStatusAndLogId);
router.post('/update-read-log-id', chatController.updateReadLogId); router.post('/update-read-log-id', chatController.updateReadLogId);
router.post('/:chatRoomId/notices', chatController.addNotice);
router.get('/:chatRoomId/notices/latest', chatController.getLatestNotice);
router.get('/:chatRoomId/notices', chatController.getAllNotices);
router.get('/:chatRoomId/notices/:noticeId', chatController.getNoticeById);
module.exports = router; module.exports = router;
//schemas/chatRooms.js
const mongoose = require('mongoose'); const mongoose = require('mongoose');
// MongoDB 채팅방 스키마 수정 (FCM 토큰을 배열로 관리)
const chatRoomsSchema = new mongoose.Schema({ const chatRoomsSchema = new mongoose.Schema({
chatRoomId: { type: String, required: true, unique: true }, chatRoomId: { type: String, required: true, unique: true },
chatRoomName: { type: String, required: true }, chatRoomName: { type: String, required: true },
...@@ -18,6 +16,11 @@ const chatRoomsSchema = new mongoose.Schema({ ...@@ -18,6 +16,11 @@ const chatRoomsSchema = new mongoose.Schema({
lastReadAt: { type: Map, of: Date }, lastReadAt: { type: Map, of: Date },
lastReadLogId: { type: Map, of: String }, lastReadLogId: { type: Map, of: String },
isOnline: { type: Map, of: Boolean }, isOnline: { type: Map, of: Boolean },
notices: [{
sender: { type: String },
message: { type: String },
timestamp: { type: Date, default: Date.now },
}]
}, { collection: 'chatrooms' }); }, { collection: 'chatrooms' });
const ChatRooms = mongoose.models.ChatRooms || mongoose.model('ChatRooms', chatRoomsSchema); const ChatRooms = mongoose.models.ChatRooms || mongoose.model('ChatRooms', chatRoomsSchema);
......
...@@ -209,6 +209,87 @@ class ChatService { ...@@ -209,6 +209,87 @@ class ChatService {
} }
} }
// 공지사항 추가
async addNotice(chatRoomId, sender, message) {
try {
const newNotice = {
sender,
message,
timestamp: new Date(),
};
const updatedChatRoom = await ChatRooms.findOneAndUpdate(
{ chatRoomId },
{ $push: { notices: newNotice } }, // 공지사항 배열에 추가
{ new: true }
);
if (!updatedChatRoom) {
throw new Error('Chat room not found');
}
return newNotice;
} catch (error) {
console.error('Error adding notice:', error.message);
throw new Error('Failed to add notice');
}
}
// 최신 공지사항 조회
async getLatestNotice(chatRoomId) {
try {
const chatRoom = await ChatRooms.findOne(
{ chatRoomId },
{ notices: { $slice: -1 } } // 최신 공지 1개만 가져오기
);
if (!chatRoom || chatRoom.notices.length === 0) {
return null;
}
return chatRoom.notices[0];
} catch (error) {
console.error('Error fetching latest notice:', error.message);
throw new Error('Failed to fetch latest notice');
}
}
// 공지사항 전체 조회
async getAllNotices(chatRoomId) {
try {
const chatRoom = await ChatRooms.findOne({ chatRoomId }, { notices: 1 });
if (!chatRoom) {
throw new Error('Chat room not found');
}
return chatRoom.notices;
} catch (error) {
console.error('Error fetching all notices:', error.message);
throw new Error('Failed to fetch all notices');
}
}
// 공지사항 상세 조회
async getNoticeById(chatRoomId, noticeId) {
try {
const chatRoom = await ChatRooms.findOne({ chatRoomId });
if (!chatRoom) {
throw new Error('Chat room not found');
}
const notice = chatRoom.notices.find(notice => notice._id.toString() === noticeId);
if (!notice) {
throw new Error('Notice not found');
}
return notice;
} catch (error) {
console.error('Error in getNoticeById:', error.message);
throw error;
}
}
} }
module.exports = new ChatService(); module.exports = new ChatService();
\ No newline at end of file
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment