Skip to content

Commit

Permalink
Merge pull request TeamMajorLink#15 from kimdavid0521/feat#12
Browse files Browse the repository at this point in the history
Feat#12 stomp 실시간 채팅 기능 구현(테스트 이전 상태)
  • Loading branch information
kimdavid0521 authored Aug 8, 2024
2 parents 24bd0d0 + 20bf84a commit fca5061
Show file tree
Hide file tree
Showing 14 changed files with 323 additions and 4 deletions.
4 changes: 4 additions & 0 deletions majorLink/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'

implementation 'org.springframework.boot:spring-boot-starter-websocket'

implementation 'org.springframework.boot:spring-boot-starter-validation'

compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'com.mysql:mysql-connector-j'
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package com.example.majorLink.controller;

import com.example.majorLink.converter.ChatRoomConverter;
import com.example.majorLink.domain.ChatMessage;
import com.example.majorLink.domain.ChatRoom;
import com.example.majorLink.dto.ChatRoomRequestDTO;
import com.example.majorLink.dto.ChatRoomResponseDTO;
import com.example.majorLink.repository.ChatRoomRepository;
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.web.bind.annotation.*;

import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@AllArgsConstructor
public class ChatController {

private final ChatService chatService;


//send message 컨트롤러
@MessageMapping("/chat.message")
@SendTo("/topic/public")
public Map<String, Object> sendMessage(Principal principal, Map<String, Object> message) {
Long sender = Long.parseLong(message.get("sender").toString());
String content = message.get("content").toString();
Integer chatRoomIdInteger = (Integer) message.get("chatroom");
long roomId = chatRoomIdInteger.longValue();

ChatRoom chatRoom = chatService.getChatroomById(roomId);

ChatMessage message1 = ChatMessage.builder()
.content(content)
.chatRoom(chatRoom)
.build();
System.out.println(message1);

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

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

result.put("id", chat.getId());
result.put("name", chat.getSender().getUserName());
result.put("content", chat.getContent());
result.put("chatroom_id", chat.getChatRoom().getId());
return result;
}





//채팅방 생성 컨트롤러
@PostMapping("/chatrooms")
public ChatRoom createChatroom(@RequestBody ChatRoomRequestDTO chatRoomRequestDTO) {
return chatService.createChatroom(chatRoomRequestDTO.getName());
}


//채팅방 전체 조회 컨트롤러
@GetMapping("/chatrooms")
public List<ChatRoomResponseDTO> getAllChatRoom() {
return chatService.getAllChatRoom().stream().map(ChatRoomConverter::toChatRoomResponseDTO).toList();
}

//채팅 기록 조회 컨트롤러
@GetMapping("/chat/history/{roomId}")
public List<ChatMessage> getChatHistory(@PathVariable Long roomId) {
return chatService.getChatMessageById(roomId);
}




}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.example.majorLink.converter;

import com.example.majorLink.domain.ChatRoom;
import com.example.majorLink.dto.ChatRoomResponseDTO;

public class ChatRoomConverter {

public static ChatRoomResponseDTO toChatRoomResponseDTO(ChatRoom chatRoom) {
return ChatRoomResponseDTO.builder()
.id(chatRoom.getId())
.name(chatRoom.getName())
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,19 @@ public class ChatMessage extends BaseEntity{
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(nullable = false, length = 20)
private String sender;

@Column(nullable = false, length = 1000)
private String content;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;
private User sender;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "chat_room_id")
private ChatRoom chatRoom;



public void setUser(User sender) {
this.sender = sender;}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ public class ChatRoom extends BaseEntity{
@Column(nullable = false, length = 20)
private String name;

@OneToMany(mappedBy = "chatRoom", cascade = CascadeType.ALL)
@Builder.Default
private List<ChatMessage> messages = new ArrayList<>();

@OneToMany(mappedBy = "chatRoom", cascade = CascadeType.ALL)
private List<UserChat> chatList = new ArrayList<>();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.example.majorLink.dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ChatRoomRequestDTO {
String name;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.example.majorLink.dto;

import lombok.Builder;
import lombok.Getter;

@Getter
@Builder
public class ChatRoomResponseDTO {
Long id;
String name;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.example.majorLink.global.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("**/")
.allowedOrigins("http://localhost:3004")
.allowedOrigins("http://localhost:3005") //프론트 테스트 url
.allowedMethods("POST", "GET", "DELETE", "PUT")
.allowedHeaders("*");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.example.majorLink.global.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
@RequiredArgsConstructor
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOriginPatterns("*");
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.example.majorLink.repository;

import com.example.majorLink.domain.ChatMessage;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface ChatMessageRepository extends JpaRepository<ChatMessage, Long> {
List<ChatMessage> findByChatRoomId(Long roomId);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.example.majorLink.repository;

import com.example.majorLink.domain.ChatRoom;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ChatRoomRepository extends JpaRepository<ChatRoom, Long> {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.example.majorLink.repository;

import com.example.majorLink.domain.mapping.UserChat;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserChatRepository extends JpaRepository<UserChat, Long> {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.example.majorLink.service;

import com.example.majorLink.domain.ChatMessage;
import com.example.majorLink.domain.ChatRoom;

import java.util.List;

public interface ChatService {

//메세지 저장
ChatMessage saveChatMessage(ChatMessage chatMessage, Long sender);

//채팅방 메세지 전체 조회
List<ChatMessage> getChatMessageById(Long roomId);

//채팅방 목록 조회
List<ChatRoom> getChatroomListById(Long userId);

//채팅방 내의 유저 닉네임 전체 조회
List<String> getChatroomUsernameById(Long roodId);

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

//채팅방 입장
Long joinRoom(Long roomId, Long userId);

ChatRoom getChatroomById(Long roomId);

//채팅방 전체조회
List<ChatRoom> getAllChatRoom();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package com.example.majorLink.service;

import com.example.majorLink.domain.ChatMessage;
import com.example.majorLink.domain.ChatRoom;
import com.example.majorLink.domain.User;
import com.example.majorLink.domain.mapping.UserChat;
import com.example.majorLink.repository.ChatMessageRepository;
import com.example.majorLink.repository.ChatRoomRepository;
import com.example.majorLink.repository.UserChatRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@AllArgsConstructor
public class ChatServiceImpl implements ChatService{

private final ChatRoomRepository chatRoomRepository;
private final ChatMessageRepository chatMessageRepository;
private final UserChatRepository userChatRepository;


//메세지 저장
@Override
public ChatMessage saveChatMessage(ChatMessage chatMessage, Long sender) {
//아직 유저 레포지토리 없어서 임시 작성
//User user = userRepository.findById(sender).orElseThroew 예외처리
//chatMessage.setUser(user);
//return chatMessageRepository.save(chatMessage);
return null;

}

//방id로 메세지 조회
@Override
public List<ChatMessage> getChatMessageById(Long roomId) {
return chatMessageRepository.findByChatRoomId(roomId);
}


//채팅방 전체 조회
@Override
public List<ChatRoom> getChatroomListById(Long userId) {
return chatRoomRepository.findAll();
}

@Override
public List<String> getChatroomUsernameById(Long roodId) {
return null;
}


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


//채팅방 입장
@Override
public Long joinRoom(Long roomId, Long userId) {
//아직 유저 레포지토리 없어서 임시작성
// ChatRoom chatRoom = chatRoomRepository.findById(roomId).orElseThrow(() -> new RuntimeException("찾는 채팅방이 없습니다"));
// User user = userRepository.findById(userId).orElseThrow(() -> new RuntimeException("찾는 유저가 없습니다"));
// UserChat userChat = UserChat.builder().chatRoom(chatRoom).user(user).build();
// return userChat.getUser().getId();
return null;
}

@Override
public ChatRoom getChatroomById(Long roomId) {
return chatRoomRepository.findById(roomId).orElseThrow(() -> new RuntimeException("해당 채팅방이 존재하지않습니다."));
}

@Override
public List<ChatRoom> getAllChatRoom() {
return chatRoomRepository.findAll();
}

}


0 comments on commit fca5061

Please sign in to comment.