@@ -3,6 +3,7 @@ import { InjectRepository } from '@nestjs/typeorm';
3
3
import { ChatRoom } from 'src/common/entities/chat-room.entity' ;
4
4
import { Matching } from 'src/common/entities/matching.entity' ;
5
5
import { StatusEnum } from 'src/common/enum/entityStatus' ;
6
+ import { MatchingRequestStatusEnum } from 'src/common/enum/matchingRequestStatus' ;
6
7
import { DataNotFoundException } from 'src/common/exception/service.exception' ;
7
8
import { CreateMatchingReqeust } from 'src/matching/dto/matching.request' ;
8
9
import { Repository , QueryRunner } from 'typeorm' ;
@@ -20,30 +21,46 @@ export class ChatRoomService {
20
21
. leftJoinAndSelect ( 'chatRoom.fromUser' , 'fromUser' )
21
22
. leftJoinAndSelect ( 'chatRoom.toUser' , 'toUser' )
22
23
. leftJoinAndSelect ( 'chatRoom.chatMessages' , 'chatMessages' )
23
- . where ( 'chatRoom.fromUserId = :userId OR chatRoom.toUserId = :userId' , {
24
- userId,
25
- } )
26
- . andWhere ( 'chatRoom.status = :status' , { status : 'activated' } )
27
- . andWhere ( 'chatRoom.requestStatus = :requestStatus' , {
28
- requestStatus : 'accepted' ,
29
- } )
24
+ . addSelect ( [
25
+ 'fromUser.id' ,
26
+ 'fromUser.nickname' ,
27
+ 'fromUser.profilePictureUrl' ,
28
+ ] )
29
+ . addSelect ( [ 'toUser.id' , 'toUser.nickname' , 'toUser.profilePictureUrl' ] )
30
+ . where (
31
+ '(chatRoom.fromUserId = :userId OR chatRoom.toUserId = :userId) AND chatRoom.status = :status AND chatRoom.requestStatus = :requestStatus' ,
32
+ {
33
+ userId,
34
+ status : StatusEnum . ACTIVATED ,
35
+ requestStatus : MatchingRequestStatusEnum . ACCEPTED ,
36
+ } ,
37
+ )
30
38
. orderBy ( 'chatMessages.createdAt' , 'DESC' )
31
39
. getMany ( ) ;
40
+ if ( ! chatRooms || chatRooms . length === 0 ) {
41
+ return [ ] ;
42
+ }
32
43
33
44
// 각 채팅방에서 최신 메시지를 선택
34
45
const chatRoomsWithLatestMessages = chatRooms . map ( ( room ) => {
35
46
const otherUser =
36
- room . fromUser . id === userId ? room . toUser : room . fromUser ;
47
+ room . fromUser && room . fromUser . id === userId
48
+ ? room . toUser
49
+ : room . fromUser ;
50
+ // fromUser나 toUser가 null인 경우, otherUser를 빈 객체로 설정
51
+ const otherUserInfo = otherUser
52
+ ? {
53
+ id : otherUser . id ,
54
+ nickname : otherUser . nickname ,
55
+ profilePictureUrl : otherUser . profilePictureUrl ,
56
+ }
57
+ : { } ;
58
+
37
59
const latestMessage =
38
60
room . chatMessages . length > 0 ? room . chatMessages [ 0 ] : null ; // 가장 최근 메시지 선택
39
-
40
61
return {
41
62
id : room . id ,
42
- otherUser : {
43
- id : otherUser . id ,
44
- nickname : otherUser . nickname ,
45
- profilePictureUrl : otherUser . profilePictureUrl ,
46
- } ,
63
+ otherUser : otherUserInfo ,
47
64
latestMessage : latestMessage ,
48
65
} ;
49
66
} ) ;
0 commit comments