Skip to content

Commit

Permalink
Merge pull request #23 from UMC6th-TeamC/chat
Browse files Browse the repository at this point in the history
채팅방 소켓 연결 엔드포인트 추가, 채팅 내역 저장 기능
  • Loading branch information
chamm99 authored Jun 23, 2024
2 parents 3e7a0de + ae28b62 commit a8a15cb
Show file tree
Hide file tree
Showing 7 changed files with 51 additions and 28 deletions.
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
package com.umc.teamC.domain.chat.controller;

import com.umc.teamC.domain.chat.entity.Chat;
import com.umc.teamC.domain.chat.entity.ChatRoom;
import com.umc.teamC.domain.chat.repository.ChatRoomRepository;
import com.umc.teamC.domain.chat.service.ChatService;
import com.umc.teamC.global.common.code.status.ErrorStatus;
import com.umc.teamC.global.common.exception.GeneralException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.HashMap;
Expand All @@ -20,36 +23,38 @@
public class ChatController {

private final ChatService chatService;
private final ChatRoomRepository chatRoomRepository;

// 메시지 보내기 컨트롤러
@MessageMapping("/chat.message")
@MessageMapping("/chat.message/{chatRoomId}")
@SendTo("/topic")
public Map<String, Object> sendMessage(
// @PathVariable Long chatRoomId,
@PathVariable Long chatRoomId,
Map<String, Object> message) {
// 메시지 확인 로그
log.info("Received message: {}", message);
String sender = message.get("sender").toString();
String content = message.get("content").toString();

Chat message1 = Chat.builder()
Chat chatMessage = Chat.builder()
.sender(sender)
.content(content)
// .chatId(chatRoomId)
.build();

Chat chat = chatService.saveMessage(message1);
chatService.saveChatMessage(chatMessage, chatRoomId);

Map<String, Object> result = new HashMap<>();
result.put("id", chat.getChatId());
result.put("sender", chat.getSender());
result.put("content", chat.getContent());
result.put("id", chatMessage.getChatId());
result.put("sender", chatMessage.getSender());
result.put("content", chatMessage.getContent());
return result;
}

@MessageMapping("/chat.addUser")
@MessageMapping("/chat.addUser/{chatRoomId}")
@SendTo("/topic")
public Chat addUser(Chat chat) {
//chat.setId(chatRoomId);
public Chat addUser(Chat chat, @PathVariable Long chatRoomId) {
ChatRoom chatRoom = chatRoomRepository.findById(chatRoomId).orElseThrow(() -> new GeneralException(ErrorStatus._NOT_FOUND_CHAT_ROOM));
chat.updateChatRoom(chatRoom);
return chat;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@
import com.umc.teamC.domain.chat.entity.Chat;
import com.umc.teamC.domain.chat.service.ChatService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import java.util.List;

Expand All @@ -17,8 +14,8 @@ class HistoryController {

private final ChatService chatService;

@GetMapping("/chat/history")
public List<Chat> getChatHistory() {
return chatService.getAllMessages();
@GetMapping("/chat/history/{chatRoomId}")
public List<Chat> getChatHistory(@PathVariable Long chatRoomId) {
return chatService.getAllMessages(chatRoomId);
}
}
4 changes: 2 additions & 2 deletions src/main/java/com/umc/teamC/domain/chat/entity/Chat.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class Chat extends BaseEntity {
@JoinColumn(name = "chat_room_id")
private ChatRoom chatRoom;

public void setId(Long id) {
chatId = id;
public void updateChatRoom(ChatRoom newRoom) {
chatRoom = newRoom;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
import com.umc.teamC.domain.chat.entity.ChatRoom;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface ChatRepository extends JpaRepository<Chat, Long> {
Chat findFirstByChatRoomOrderByCreatedAtDesc(ChatRoom chatRoom);

List<Chat> findAllByChatRoom(ChatRoom chatRoom);
}
25 changes: 19 additions & 6 deletions src/main/java/com/umc/teamC/domain/chat/service/ChatService.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
package com.umc.teamC.domain.chat.service;

import com.umc.teamC.domain.chat.entity.Chat;
import com.umc.teamC.domain.chat.entity.ChatRoom;
import com.umc.teamC.domain.chat.repository.ChatRepository;
import com.umc.teamC.domain.chat.repository.ChatRoomRepository;
import com.umc.teamC.global.common.code.status.ErrorStatus;
import com.umc.teamC.global.common.exception.GeneralException;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
Expand All @@ -10,18 +15,26 @@

@Service
@RequiredArgsConstructor
@Transactional
public class ChatService {

private final ChatRepository chatRepository;
private final ChatRoomRepository chatRoomRepository;
private final SimpMessagingTemplate template;

SimpMessagingTemplate template;
public void saveChatMessage(Chat chatMessage, Long roomId) {
ChatRoom chatRoom = chatRoomRepository.findById(roomId)
.orElseThrow(() -> new GeneralException(ErrorStatus._NOT_FOUND_CHAT_ROOM));
chatMessage.updateChatRoom(chatRoom);
chatRepository.save(chatMessage);

public Chat saveMessage(Chat chat) {
// template.convertAndSend("/topic/public" + sessionId, message);
return chatRepository.save(chat);
template.convertAndSend("/topic/" + roomId, chatMessage);
}

public List<Chat> getAllMessages() {
return chatRepository.findAll();
public List<Chat> getAllMessages(Long chatRoomId) {
ChatRoom chatRoom = chatRoomRepository.findById(chatRoomId)
.orElseThrow(() -> new GeneralException(ErrorStatus._NOT_FOUND_CHAT_ROOM));
return chatRepository.findAllByChatRoom(chatRoom);
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,13 @@ public enum ErrorStatus implements BaseErrorCode {

_AUTHENTICATION_FAILED(HttpStatus.UNAUTHORIZED, "AUTH403", "로그인 실패."),

// 채팅방 에러
_NOT_FOUND_CHAT_ROOM(HttpStatus.NOT_FOUND, "ROOM400", "해당 채팅방이 존재하지 않습니다."),

// User 에러
_NOT_FOUND_USER(HttpStatus.NOT_FOUND, "USER400", "사용자가 존재하지 않습니다.");


private final HttpStatus httpStatus;
private final String code;
private final String message;
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/umc/teamC/global/util/RedisUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,4 @@ public Object get(String key) {
public boolean delete(String key) {
return Boolean.TRUE.equals(redisTemplate.delete(key));
}
}
}

0 comments on commit a8a15cb

Please sign in to comment.