diff --git a/backend/src/messages/messages.controller.ts b/backend/src/messages/messages.controller.ts index bbe4831..77bc553 100644 --- a/backend/src/messages/messages.controller.ts +++ b/backend/src/messages/messages.controller.ts @@ -22,6 +22,11 @@ export class MessagesController { return this.messagesService.getConversations(req.user.sub); } + @Get("unread-count") + getUnreadCount(@Req() req: AuthenticatedRequest) { + return this.messagesService.getUnreadCount(req.user.sub); + } + @Get("conversations/with/:userId") getConversationWithUser( @Req() req: AuthenticatedRequest, diff --git a/backend/src/messages/messages.service.ts b/backend/src/messages/messages.service.ts index 0e89ca7..0d98d3d 100644 --- a/backend/src/messages/messages.service.ts +++ b/backend/src/messages/messages.service.ts @@ -42,6 +42,10 @@ export class MessagesService { return this.messagesRepository.findAllConversations(userId); } + async getUnreadCount(userId: string) { + return this.messagesRepository.countUnreadMessages(userId); + } + async getConversationWithUser(userId: string, targetUserId: string) { return this.messagesRepository.findConversationBetweenUsers( userId, diff --git a/backend/src/messages/repositories/messages.repository.ts b/backend/src/messages/repositories/messages.repository.ts index 790b5f2..11f1225 100644 --- a/backend/src/messages/repositories/messages.repository.ts +++ b/backend/src/messages/repositories/messages.repository.ts @@ -133,4 +133,35 @@ export class MessagesRepository { .from(conversationParticipants) .where(eq(conversationParticipants.conversationId, conversationId)); } + + async markAsRead(conversationId: string, userId: string) { + await this.databaseService.db + .update(messages) + .set({ readAt: new Date() }) + .where( + and( + eq(messages.conversationId, conversationId), + sql`${messages.senderId} != ${userId}`, + sql`${messages.readAt} IS NULL`, + ), + ); + } + + async countUnreadMessages(userId: string) { + const result = await this.databaseService.db + .select({ count: sql`count(*)` }) + .from(messages) + .innerJoin( + conversationParticipants, + eq(messages.conversationId, conversationParticipants.conversationId), + ) + .where( + and( + eq(conversationParticipants.userId, userId), + sql`${messages.senderId} != ${userId}`, + sql`${messages.readAt} IS NULL`, + ), + ); + return Number(result[0]?.count || 0); + } } diff --git a/frontend/src/services/message.service.ts b/frontend/src/services/message.service.ts index 168b282..73295a9 100644 --- a/frontend/src/services/message.service.ts +++ b/frontend/src/services/message.service.ts @@ -29,6 +29,11 @@ export const MessageService = { return data; }, + async getUnreadCount(): Promise { + const { data } = await api.get("/messages/unread-count"); + return data; + }, + async getMessages(conversationId: string): Promise { const { data } = await api.get( `/messages/conversations/${conversationId}`,