Skip to content

Commit 8941fdf

Browse files
committed
Feat: 채팅방 전체 조회, 생성 조회
1 parent f35ddd4 commit 8941fdf

File tree

12 files changed

+251
-8
lines changed

12 files changed

+251
-8
lines changed

src/main/java/cmf/commitField/domain/chat/chatRoom/controller/ChatRoomController.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,22 @@
11
package cmf.commitField.domain.chat.chatRoom.controller;
22

33
import cmf.commitField.domain.chat.chatRoom.controller.request.ChatRoomRequest;
4+
import cmf.commitField.domain.chat.chatRoom.dto.ChatRoomDto;
45
import cmf.commitField.domain.chat.chatRoom.service.ChatRoomService;
56
import cmf.commitField.domain.user.entity.CustomOAuth2User;
67
import cmf.commitField.global.globalDto.GlobalResponse;
8+
import cmf.commitField.global.security.LoginCheck;
79
import jakarta.validation.Valid;
810
import lombok.RequiredArgsConstructor;
11+
import org.springframework.data.domain.Pageable;
12+
import org.springframework.http.ResponseEntity;
913
import org.springframework.security.core.Authentication;
1014
import org.springframework.security.core.context.SecurityContextHolder;
1115
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
1216
import org.springframework.web.bind.annotation.*;
1317

18+
import java.util.List;
19+
1420
@RestController
1521
@RequiredArgsConstructor
1622
@RequestMapping("/chat")
@@ -47,4 +53,30 @@ public GlobalResponse<Object> joinRoom(@PathVariable Long roomId) {
4753
throw new IllegalArgumentException("User not logged in.");
4854
}
4955
}
56+
57+
// 전체 리스트
58+
@GetMapping("/room")
59+
@LoginCheck
60+
public ResponseEntity<Object> roomList(Pageable pageable) {
61+
List<ChatRoomDto> roomList = chatRoomService.getRoomList(pageable);
62+
return ResponseEntity.ok().body(roomList);
63+
}
64+
65+
// 사용자(자신)가 생성한 방 리스트 조회
66+
@GetMapping("/room/creator")
67+
@LoginCheck
68+
public ResponseEntity<Object> getByUserRoomList(Pageable pageable) {
69+
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
70+
71+
if (authentication instanceof OAuth2AuthenticationToken) {
72+
CustomOAuth2User principal = (CustomOAuth2User) authentication.getPrincipal();
73+
Long userId = principal.getId(); // getId()를 통해 userId를 추출
74+
75+
List<ChatRoomDto> userByRoomList = chatRoomService.getUserByRoomList(userId, pageable);
76+
return ResponseEntity.ok().body(userByRoomList);
77+
} else {
78+
throw new IllegalArgumentException("User not logged in.");
79+
}
80+
}
81+
5082
}
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package cmf.commitField.domain.chat.chatRoom.controller.response;
2-
3-
public class ChatRoomResponse {
4-
}
1+
//package cmf.commitField.domain.chat.chatRoom.controller.response;
2+
//
3+
//public class ChatRoomResponse {
4+
//}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package cmf.commitField.domain.chat.chatRoom.dto;
2+
3+
import lombok.*;
4+
5+
@Getter
6+
@Setter
7+
@NoArgsConstructor
8+
@AllArgsConstructor
9+
@Builder
10+
public class ChatRoomDto {
11+
private Long id;
12+
13+
private String title;
14+
15+
private Long currentUserCount;
16+
17+
private Integer userCountMax;
18+
}

src/main/java/cmf/commitField/domain/chat/chatRoom/entity/ChatRoom.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,18 @@ public class ChatRoom extends BaseEntity {
3535

3636
@OneToMany(mappedBy = "chatRoom", fetch = FetchType.LAZY)
3737
private List<ChatMessage> chatMessages;
38+
39+
@Override
40+
public String toString() {
41+
return "ChatRoom{" +
42+
// BaseEntity에서 상속받은 id 사용
43+
"id=" + getId() +
44+
", title='" + title + '\'' +
45+
", tier='" + tier + '\'' +
46+
", roomCreator=" + roomCreator +
47+
", userCountMax=" + userCountMax +
48+
", user=" + (user != null ? user.getId() : "null") + // user가 null일 수 있기 때문에 체크
49+
", userChatRooms=" + (userChatRooms != null ? userChatRooms.size() : 0) + // userChatRooms 리스트가 null일 수 있기 때문에 체크
50+
'}';
51+
}
3852
}

src/main/java/cmf/commitField/domain/chat/chatRoom/repository/ChatRoomRepository.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,13 @@
33
import cmf.commitField.domain.chat.chatRoom.entity.ChatRoom;
44
import jakarta.persistence.LockModeType;
55
import jakarta.persistence.QueryHint;
6+
import org.springframework.data.domain.Page;
7+
import org.springframework.data.domain.Pageable;
68
import org.springframework.data.jpa.repository.JpaRepository;
79
import org.springframework.data.jpa.repository.Lock;
10+
import org.springframework.data.jpa.repository.Query;
811
import org.springframework.data.jpa.repository.QueryHints;
12+
import org.springframework.data.repository.query.Param;
913
import org.springframework.stereotype.Repository;
1014

1115
import java.util.Optional;
@@ -16,4 +20,12 @@ public interface ChatRoomRepository extends JpaRepository<ChatRoom, Long> {
1620
@Lock(LockModeType.PESSIMISTIC_WRITE)
1721
@QueryHints({@QueryHint(name = "javax.persistence.lock.timeout", value ="1000")})
1822
Optional<ChatRoom> findById(Long aLong);
23+
24+
@Query("select c from ChatRoom c where c.roomCreator=:userId")
25+
Page<ChatRoom> findAllByUserId(@Param("userId")Long userId,Pageable pageable);
26+
27+
// Page<ChatRoom> findAllByUserChatRoomsUserId(Long userId,Pageable pageable);
28+
29+
// @Query(value = "SELECT ROOM_CREATOR FROM chat_room WHERE CHAT_ROOM_ID = ?", nativeQuery = true)
30+
// Long findChatRoomByRoomCreator(Long roomId);
1931
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,26 @@
11
package cmf.commitField.domain.chat.chatRoom.service;
22

33
import cmf.commitField.domain.chat.chatRoom.controller.request.ChatRoomRequest;
4+
import cmf.commitField.domain.chat.chatRoom.dto.ChatRoomDto;
5+
import org.springframework.data.domain.Pageable;
6+
7+
import java.util.List;
48

59
public interface ChatRoomService {
610

711
void createRoom(ChatRoomRequest chatRoomRequest, Long userId); // userId를 받도록 수정
812

913
void joinRoom(Long roomId, Long userId); // userId를 받도록 수정
14+
15+
// 채팅방 전체 조회
16+
List<ChatRoomDto> getRoomList(Pageable pageable);
17+
18+
// 자신이 생성한 방 리스트 조회
19+
List<ChatRoomDto> getUserByRoomList(Long userId, org.springframework.data.domain.Pageable pageable);
20+
21+
// List<ChatRoomDto> getUserByRoomPartList(Long userId, Pageable pageable);
22+
//
23+
// void outRoom(Long userId, Long roomId);
24+
//
25+
// void deleteRoom(Long userId, Long roomId);
1026
}

src/main/java/cmf/commitField/domain/chat/chatRoom/service/ChatRoomServiceImpl.java

Lines changed: 81 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package cmf.commitField.domain.chat.chatRoom.service;
22

3+
import cmf.commitField.domain.chat.chatMessage.repository.ChatMessageRepository;
34
import cmf.commitField.domain.chat.chatRoom.controller.request.ChatRoomRequest;
5+
import cmf.commitField.domain.chat.chatRoom.dto.ChatRoomDto;
46
import cmf.commitField.domain.chat.chatRoom.entity.ChatRoom;
57
import cmf.commitField.domain.chat.chatRoom.repository.ChatRoomRepository;
68
import cmf.commitField.domain.chat.userChatRoom.entity.UserChatRoom;
@@ -9,11 +11,15 @@
911
import cmf.commitField.domain.user.repository.UserRepository;
1012
import cmf.commitField.global.error.ErrorCode;
1113
import cmf.commitField.global.exception.CustomException;
12-
import jakarta.transaction.Transactional;
1314
import lombok.RequiredArgsConstructor;
15+
import org.springframework.data.domain.Page;
16+
import org.springframework.data.domain.Pageable;
1417
import org.springframework.stereotype.Service;
18+
import org.springframework.transaction.annotation.Transactional;
1519

1620
import java.time.LocalDateTime;
21+
import java.util.ArrayList;
22+
import java.util.List;
1723

1824
@Service
1925
@RequiredArgsConstructor
@@ -22,6 +28,7 @@ public class ChatRoomServiceImpl implements ChatRoomService {
2228
private final ChatRoomRepository chatRoomRepository;
2329
private final UserRepository userRepository;
2430
private final UserChatRoomRepository userChatRoomRepository;
31+
private final ChatMessageRepository chatMessageRepository;
2532

2633
@Override
2734
@Transactional
@@ -74,4 +81,77 @@ public void joinRoom(Long roomId, Long userId) {
7481
.build();
7582
userChatRoomRepository.save(userChatRoom);
7683
}
84+
85+
//// chatMsgRepository.deleteById(roomId); 방 삭제 시 채팅도 다 삭제 되어야 함.
86+
// }
87+
//
88+
// 방 조회 DTO 변환 메서드 추출
89+
private static List<ChatRoomDto> getChatRoomDtos(Page<ChatRoom> all) {
90+
List<ChatRoomDto> chatRoomList = new ArrayList<>();
91+
92+
for (ChatRoom list : all) {
93+
ChatRoomDto dto = ChatRoomDto.builder()
94+
.id(list.getId())
95+
.title(list.getTitle())
96+
.currentUserCount((long) list.getUserChatRooms().size())
97+
.userCountMax(list.getUserCountMax())
98+
.build();
99+
100+
chatRoomList.add(dto);
101+
}
102+
return chatRoomList;
103+
}
104+
105+
// 채팅방 전체 조회
106+
@Override
107+
// @Transactional(readOnly = true)
108+
public List<ChatRoomDto> getRoomList(Pageable pageable) {
109+
Page<ChatRoom> all = chatRoomRepository.findAll(pageable);
110+
return getChatRoomDtos(all);
111+
}
112+
113+
// // 자신이 참여한 방 리스트 조회
114+
// @Override
115+
// public List<ChatRoomDto> getUserByRoomPartList(Long userId, Pageable pageable) {
116+
// Page<ChatRoom> allByUserIdAndUserChatRooms = chatRoomRepository
117+
// .findAllByUserChatRoomsUserId(userId, pageable);
118+
// return getChatRoomDtos(allByUserIdAndUserChatRooms);
119+
// }
120+
121+
// @Override
122+
// @Transactional
123+
// public void outRoom(Long userId, Long roomId) {
124+
// Long roomCreatorId = chatRoomRepository
125+
// .findChatRoomByRoomCreator(roomId);
126+
// // 방장이 아니라면
127+
// if (!Objects.equals(roomCreatorId, userId)) {
128+
// userChatRoomRepository.deleteUserChatRoomByUserId(userId);
129+
// return;
130+
// }
131+
// // 방장이라면 방 삭제
132+
// userChatRoomRepository.deleteUserChatRoomByChatRoom_Id(roomId);
133+
// chatRoomRepository.deleteById(roomId);
134+
// }
135+
//
136+
// @Override
137+
// @Transactional
138+
// public void deleteRoom(Long userId, Long roomId) {
139+
// Long roomCreatorId = chatRoomRepository
140+
// .findChatRoomByRoomCreator(roomId);
141+
// if (!Objects.equals(roomCreatorId, userId)) {
142+
// throw new CustomException(ErrorCode.NOT_ROOM_CREATOR);
143+
// }
144+
// userChatRoomRepository.deleteUserChatRoomByChatRoom_Id(roomId);
145+
// chatRoomRepository.deleteById(roomId);
146+
// // todo : 채팅 메시지 구현 시, 방 삭제할 때 메시지도 같이 삭제되는 메서드 구현
147+
148+
// 자신이 생성한 방 리스트 조회
149+
@Override
150+
//
151+
public List<ChatRoomDto> getUserByRoomList(Long userId, Pageable pageable) {
152+
Page<ChatRoom> all = chatRoomRepository.findAllByUserId(userId, pageable);
153+
return getChatRoomDtos(all);
154+
}
155+
156+
77157
}

src/main/java/cmf/commitField/domain/chat/userChatRoom/repository/UserChatRoomRepository.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import org.springframework.data.jpa.repository.Lock;
88
import org.springframework.data.jpa.repository.Query;
99
import org.springframework.data.jpa.repository.QueryHints;
10+
import org.springframework.data.repository.query.Param;
1011
import org.springframework.stereotype.Repository;
1112

1213
@Repository
@@ -16,6 +17,12 @@ public interface UserChatRoomRepository extends JpaRepository<UserChatRoom, Long
1617
@QueryHints({@QueryHint(name = "javax.persistence.lock.timeout", value = "1000")})
1718
Long countByChatRoomId(Long roomId); // 비관적 락
1819

19-
@Query("select count(*) from UserChatRoom u where u.chatRoom.id = ?1 ")
20-
Long countNonLockByChatRoomId(Long roomId); // test 용도
20+
// @Query("select count(*) from UserChatRoom u where u.chatRoom.id = ?1 ")
21+
// Long countNonLockByChatRoomId(Long roomId); // test 용도
22+
@Query("select count(*) from UserChatRoom u where u.chatRoom.id = :roomId")
23+
Long countNonLockByChatRoomId(@Param("roomId")Long roomId); // test 용도
24+
25+
void deleteUserChatRoomByChatRoom_Id(Long chatRoomId);
26+
27+
void deleteUserChatRoomByUserId(Long userId);
2128
}

src/main/java/cmf/commitField/global/error/ErrorCode.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,10 @@ public enum ErrorCode {
3535

3636
//chatroom
3737
NOT_FOUND_ROOM(HttpStatus.NOT_FOUND, "이미 삭제된 방이거나 방을 찾을 수 없습니다."),
38-
ROOM_USER_FULL(HttpStatus.BAD_REQUEST, "방에 사용자가 다 차 있습니다.");
38+
ROOM_USER_FULL(HttpStatus.BAD_REQUEST, "방에 사용자가 다 차 있습니다."),
39+
NONE_ROOM(HttpStatus.NOT_FOUND, "현재 방이 없습니다."),
40+
CHAT_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "채팅 전송에 오류가 있습니다."),
41+
NOT_ROOM_CREATOR(HttpStatus.FORBIDDEN, "방 생성자가 아닙니다.");
3942

4043
private final HttpStatus httpStatus;
4144
private final String message;
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package cmf.commitField.global.security;
2+
3+
import java.lang.annotation.ElementType;
4+
import java.lang.annotation.Retention;
5+
import java.lang.annotation.RetentionPolicy;
6+
import java.lang.annotation.Target;
7+
8+
@Target(ElementType.METHOD) // 메서드에 적용
9+
@Retention(RetentionPolicy.RUNTIME) // 런타임 시에 적용
10+
public @interface LoginCheck {
11+
}

0 commit comments

Comments
 (0)