diff --git a/src/chat/repositories/chat.repository.ts b/src/chat/repositories/chat.repository.ts index 20a009d..e5cdb74 100644 --- a/src/chat/repositories/chat.repository.ts +++ b/src/chat/repositories/chat.repository.ts @@ -76,7 +76,7 @@ export class ChatRepository { // 채팅방을 나갔으면 그 이후의 메세지만 조회 if (leftAt) { - whereConditions.created_at = { gt: leftAt }; + whereConditions.sent_at = { gt: leftAt }; } const [messages, totalCount] = await Promise.all([ @@ -105,6 +105,7 @@ export class ChatRepository { return { messages: actualMessages, totalCount, + hasMore: hasNextPage, }; } @@ -258,14 +259,16 @@ export class ChatRepository { } // == 메세지 저장 - async saveMessage( - roomId: number, - senderId: number, - content: string, - files: { url: string; contentType: AttachmentType; name: string; size: number }[] - ) { - - return prisma.chatMessage.create({ +async saveMessage( + roomId: number, + senderId: number, + content: string, + files: { url: string; contentType: AttachmentType; name: string; size: number }[] +) { + // 트랜잭션으로 메세지 생성과 채팅방 업데이트를 묶어서 처리 + return prisma.$transaction(async (tx) => { + // 1. 메세지 생성 + const savedMessage = await tx.chatMessage.create({ data: { room_id: roomId, sender_id: senderId, @@ -290,8 +293,14 @@ export class ChatRepository { attachments: true, }, }); - } - -} + // 2. 채팅방의 마지막 메세지 ID 업데이트 + await tx.chatRoom.update({ + where: { room_id: roomId }, + data: { last_message_id: savedMessage.message_id }, + }); + return savedMessage; + }); +} +} diff --git a/src/chat/services/chat.service.ts b/src/chat/services/chat.service.ts index 9e313a1..87d5302 100644 --- a/src/chat/services/chat.service.ts +++ b/src/chat/services/chat.service.ts @@ -63,10 +63,9 @@ export class ChatService { this.chatRepo.findMessagesByRoomId(roomId, cursor, limit, myId), updateReadStatus ]); - - // 페이지네이션 - const hasMore = messageInfo.messages.length > limit; - const messages = hasMore ? messageInfo.messages.slice(0, limit) : messageInfo.messages; + + const hasMore = messageInfo.hasMore; + const messages = messageInfo.messages; return ChatRoomDetailResponseDto.from({ roomDetail, @@ -88,7 +87,6 @@ export class ChatService { filter, search }); - // 페이지네이션 const hasMore = roomList.rooms.length > limit;