Skip to content

Commit

Permalink
Merge pull request TeamMajorLink#99 from kimdavid0521/feat#90
Browse files Browse the repository at this point in the history
[Refactor] 채팅 리팩토링
  • Loading branch information
kimdavid0521 authored Aug 22, 2024
2 parents b4364c4 + 7c35e17 commit 784c1e4
Show file tree
Hide file tree
Showing 7 changed files with 52 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,51 +3,59 @@

import com.example.majorLink.domain.ChatMessage;
import com.example.majorLink.domain.ChatRoom;
import com.example.majorLink.domain.User;
import com.example.majorLink.dto.*;
import com.example.majorLink.global.auth.AuthUser;
import com.example.majorLink.repository.UserRepository;
import com.example.majorLink.service.ChatService;
import lombok.AllArgsConstructor;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.*;

@RestController
@AllArgsConstructor
public class ChatController {

private final ChatService chatService;

private final UserRepository userRepository;

//send message 컨트롤러
@MessageMapping("/chat.message")
@SendTo("/topic/public")
public Map<String, Object> sendMessage(Map<String, Object> message) {
UUID sender = UUID.fromString(message.get("sender").toString());
// User user = authUser.getUser();
// String username = user.getUsername();

User user = userRepository.findById(sender).orElseThrow(() ->
new IllegalArgumentException("유저를 찾을 수 없습니다: " + sender));

String content = message.get("content").toString();
Integer chatRoomIdInteger = (Integer) message.get("chatroom");
long roomId = chatRoomIdInteger.longValue();

// 로그 추가
System.out.println("Received message: " + content);
System.out.println("Sender UUID: " + sender);
System.out.println("username: " + user.getUsername());
System.out.println("Room ID: " + roomId);

ChatRoom chatRoom = chatService.getChatroomById(roomId);

ChatMessage message1 = ChatMessage.builder()
.content(content)
.chatRoom(chatRoom)
.sender(user)
.build();

// 로그 추가
System.out.println("Saving message: " + message1);


ChatMessage chat = chatService.saveChatMessage(message1, sender);
ChatMessage chat = chatService.saveChatMessage(message1, user);

Map<String, Object> result = new HashMap<>();

Expand All @@ -61,8 +69,9 @@ public Map<String, Object> sendMessage(Map<String, Object> message) {

//채팅방 생성 컨트롤러
@PostMapping("/chatrooms")
public ChatRoom createChatroom(@RequestBody ChatRoomRequestDTO chatRoomRequestDTO) {
return chatService.createChatroom(chatRoomRequestDTO.getName());
public ChatRoom createChatroom(@RequestBody ChatRoomRequestDTO chatRoomRequestDTO, @AuthenticationPrincipal AuthUser authUser) {
User user = authUser.getUser();
return chatService.createChatroom(chatRoomRequestDTO.getName(), user);
}


Expand All @@ -81,17 +90,17 @@ public List<ChatRoomResponseDTO> getAllChatRoom() {
public List<ChatmessageResponseDTO> getChatHistory(@PathVariable Long roomId) {
return chatService.getChatMessageById(roomId).stream().map(chatMessage -> ChatmessageResponseDTO.builder()
.id(chatMessage.getId())
.senderUsername(chatMessage.getSender().getUsername())
.name(chatMessage.getSender().getUsername())
.content(chatMessage.getContent())
.chatroomId(chatMessage.getChatRoom().getId())
.build())
.toList();
}

//채팅방 입장 컨트롤러
@PostMapping("/chat/join")
public String joinRoom(@RequestBody ChatjoinRequestDTO chatjoinRequestDTO) {
return chatService.joinRoom(chatjoinRequestDTO.getRoomId(), chatjoinRequestDTO.getUserId());
@PostMapping("/chat/join/{roomId}")
public String joinRoom(@PathVariable Long roomId, @AuthenticationPrincipal AuthUser authUser) {
return chatService.joinRoom(roomId, authUser.getUser());
}

//채팅방별 입장한 유저 조회
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,6 @@ public class ChatRoom extends BaseEntity{

@OneToMany(mappedBy = "chatRoom", cascade = CascadeType.ALL)
private List<UserChat> chatList = new ArrayList<>();


}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.example.majorLink.dto;

import com.example.majorLink.domain.User;
import lombok.Builder;
import lombok.Getter;

Expand All @@ -9,5 +10,5 @@
@Builder
public class ChatjoinRequestDTO {
private Long roomId;
private UUID userId;

}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
public class ChatmessageResponseDTO {
private Long id;
private String content;
private String senderUsername;
private String name;
private Long chatroomId;

}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000",
.allowedOrigins("http://localhost:3000","http://localhost:3003","http://localhost:3004",
"http://localhost:3007","http://localhost:3008",
"http://localhost:59923",
"http://localhost:3003",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
public interface ChatService {

//메세지 저장
ChatMessage saveChatMessage(ChatMessage chatMessage, UUID sender);
ChatMessage saveChatMessage(ChatMessage chatMessage, User user);

//채팅방 메세지 전체 조회
List<ChatMessage> getChatMessageById(Long roomId);
Expand All @@ -23,10 +23,10 @@ public interface ChatService {
List<User> getUserById(Long roomId);

//채팅방 생성
ChatRoom createChatroom(String roomName);
ChatRoom createChatroom(String roomName, User user);

//채팅방 입장
String joinRoom(Long roomId, UUID userId);
String joinRoom(Long roomId, User user);

ChatRoom getChatroomById(Long roomId);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import com.example.majorLink.repository.UserChatRepository;
import com.example.majorLink.repository.UserRepository;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
Expand All @@ -25,10 +27,9 @@ public class ChatServiceImpl implements ChatService{
private final UserRepository userRepository;


//메세지 저장

@Override
public ChatMessage saveChatMessage(ChatMessage chatMessage, UUID sender) {
User user = userRepository.findById(sender).orElseThrow(() -> new RuntimeException("존재하지않는 유저입니다")); //예외처리 부분 추후 수정
public ChatMessage saveChatMessage(ChatMessage chatMessage, User user) {
// 로그 추가
System.out.println("User found: " + user);

Expand All @@ -37,9 +38,7 @@ public ChatMessage saveChatMessage(ChatMessage chatMessage, UUID sender) {
// 로그 추가
System.out.println("Saving chat message: " + chatMessage);


return chatMessageRepository.save(chatMessage);

}

//방id로 메세지 조회
Expand All @@ -63,22 +62,32 @@ public List<User> getUserById(Long roomId) {
.collect(Collectors.toList()); //List<User>로 변환
}




//채팅방 생성
@Override
public ChatRoom createChatroom(String roomName) {
public ChatRoom createChatroom(String roomName, User user) {
ChatRoom chatRoom = ChatRoom.builder()
.name(roomName)
.build();
// UserChat userChat = UserChat.builder()
// .chatRoom(chatRoom)
// .user(user)
// .build();
return chatRoomRepository.save(chatRoom);
}


//채팅방 생성
// @Override
// public ChatRoom createChatroom(String roomName) {
// ChatRoom chatRoom = ChatRoom.builder()
// .name(roomName)
// .build();
// return chatRoomRepository.save(chatRoom);
// }


//채팅방 입장
public String joinRoom(Long roomId, UUID userId) {
User user = userRepository.findById(userId).orElseThrow(() -> new RuntimeException("존재하지 않는 유저 입니다"));
public String joinRoom(Long roomId, User user) {

ChatRoom chatRoom = chatRoomRepository.findById(roomId).orElseThrow(() -> new RuntimeException("존재하지 않는 채팅방입니다"));
UserChat userChat = UserChat.builder()
.user(user)
Expand Down

0 comments on commit 784c1e4

Please sign in to comment.