Skip to content

Commit

Permalink
style : 채팅 코드 예외 처리 및 코드 리팩토링
Browse files Browse the repository at this point in the history
  • Loading branch information
fnzl54 committed Mar 8, 2024
1 parent 5809f2f commit 7d25fbb
Show file tree
Hide file tree
Showing 16 changed files with 112 additions and 117 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,11 @@

@Controller
@RequiredArgsConstructor
//@RequestMapping("/api/chat") - ws에서 지원 x
public class ChatController {

private final SimpMessageSendingOperations template;
private final ChatService chatService;

// // 처음 시작하는 체팅 -> 채팅방 제작
// // 기존에 존재하는 채팅 -> 채팅방 id 반환만
// @MessageMapping("/api/chat/enterRoom")
// public void enterUser(@Payload ChatReq chat) {
//
// }

@MessageMapping("/api/chat/sendMessage")
public void sendMessage(@Payload ChatReq chat) {
chatService.saveMessage(chat);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,6 @@ public ResponseEntity<ChatCreateRes> createRoom(
return ResponseEntity.status(HttpStatus.CREATED).body(chatCreateRes);
}



/*
* @Describe : 채팅방 리스트 조회
* @Param1 : userDetailsImpl(UserDetailsImpl) 로그인 유저
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
package com.teamjo.techeermarket.domain.chats.dto.request;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ChatReq {
private Long chatRoomId; // 방 번호
private String senderEmail;
private String message;
private String createdAt;

}
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
package com.teamjo.techeermarket.domain.chats.dto.request;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ChatRoomCreateReq {
private Long productId;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
package com.teamjo.techeermarket.domain.chats.dto.response;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ChatCreateRes {
private Long chatRoomId;
private ProductInfo productInfo;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
package com.teamjo.techeermarket.domain.chats.dto.response;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ChatInfo {
private String senderEmail;
private String message;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
package com.teamjo.techeermarket.domain.chats.dto.response;

import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ChatRes {
private ProductInfo productInfo;
private String chatCreateAt;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
package com.teamjo.techeermarket.domain.chats.dto.response;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ChatRoomRes {
private Long id;
private Long productId;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,34 +1,18 @@
package com.teamjo.techeermarket.domain.chats.dto.response;

import com.teamjo.techeermarket.domain.products.entity.ProductState;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ProductInfo {
private Long productId ;

private String title ;

private String thumbnailURL; // 썸네일 이미지

private String name; // 작성자

private Long userId ; // 작성자 id

private int price ;

private String createdAt ;

private int likes ; // 좋아요수

private int views; // 뷰 수


}
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package com.teamjo.techeermarket.domain.chats.mapper;

import com.teamjo.techeermarket.domain.chats.dto.response.ChatCreateRes;
import com.teamjo.techeermarket.domain.chats.dto.response.ChatInfo;
import com.teamjo.techeermarket.domain.chats.dto.response.ChatRes;
import com.teamjo.techeermarket.domain.chats.dto.response.ProductInfo;
import com.teamjo.techeermarket.domain.chats.entity.Chat;
import com.teamjo.techeermarket.domain.chats.entity.ChatRoom;
import com.teamjo.techeermarket.domain.products.entity.Products;
import java.util.List;
import org.springframework.stereotype.Component;

@Component
Expand All @@ -25,17 +28,18 @@ public ChatInfo toChatResDtoList(Chat chat) {
.build();
}

public ProductInfo toProductInfo(Products product){
return ProductInfo.builder()
.productId(product.getId())
.title(product.getTitle())
.thumbnailURL(product.getThumbnail())
.name(product.getUsers().getName())
.userId(product.getUsers().getId())
.price(product.getPrice())
.createdAt(product.getCreatedAt())
.likes(product.getHeart())
.views(product.getViews())
public ChatRes toChatResDto (List<ChatInfo> response, ProductInfo productInfo, String chatCreateAt) {
return ChatRes.builder()
.chatInfoList(response)
.productInfo(productInfo)
.chatCreateAt(chatCreateAt)
.build();
}

public ChatCreateRes toChatCreateResDto (Long chatRoomId, ProductInfo productInfo) {
return ChatCreateRes.builder()
.chatRoomId(chatRoomId)
.productInfo(productInfo)
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@
import com.teamjo.techeermarket.domain.chats.repository.ChatRepository;
import com.teamjo.techeermarket.domain.chats.repository.ChatRoomRepository;
import com.teamjo.techeermarket.domain.products.entity.Products;
import com.teamjo.techeermarket.domain.products.mapper.ProductMapper;
import com.teamjo.techeermarket.domain.products.repository.ProductRepository;
import com.teamjo.techeermarket.domain.users.repository.UserRepository;
import com.teamjo.techeermarket.global.exception.product.ProductNotFoundException;
import com.teamjo.techeermarket.global.exception.user.UserNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
Expand All @@ -33,58 +35,67 @@ public class ChatRoomService {
private final ChatRoomMapper chatRoomMapper;
private final UserRepository userRepository;
private final ChatMapper chatMapper;
private final ProductMapper productMapper;

@Transactional
public ChatCreateRes createChatRoom(Long productId, String buyer) {

Optional<Products> product = productRepository.findById(productId);
Products product = productRepository.findById(productId)
.orElseThrow(ProductNotFoundException::new);;

ChatRoom chatRoom = chatRoomMapper.toEntity(product.get(), product.get().getUsers().getEmail(), buyer);
ChatRoom chatRoom = chatRoomMapper.toEntity(product, product.getUsers().getEmail(), buyer);
ChatRoom save = chatRoomRepository.save(chatRoom);

Products products = productRepository.findById(productId).get();
ProductInfo productInfo = chatMapper.toProductInfo(products);
ProductInfo productInfo = productMapper.toProductInfo(product);

ChatCreateRes chatCreateRes = new ChatCreateRes();
chatCreateRes.setChatRoomId(save.getId());
chatCreateRes.setProductInfo(productInfo);

return chatCreateRes;
return chatMapper.toChatCreateResDto(save.getId(), productInfo);
}

@Transactional(readOnly = true)
public List<ChatRoomRes> findChatRoomByUserId(String userEmail, int pageNo, int pageSize) {
Pageable pageable = PageRequest.of(pageNo - 1, pageSize, Sort.by("id").descending()); // 1페이지부터 시작하도록
Page<Object[]> results = chatRoomRepository.findByUserIn(userEmail, pageable);

List<ChatRoomRes> chatRoomResponse = new ArrayList<>();
for (Object[] result : results) {
Long id = (Long) result[0];
Long productId = (Long) result[1];
String productTitle = (String) result[2];
String productLocation = (String) result[3];
int productPrice = (int) result[4];
String productThumbnail = (String) result[5];
String sellerEmail = (String) result[6];
String buyerEmail = (String) result[7];

String chatPartnerEmail = userEmail.equals(sellerEmail) ? buyerEmail : sellerEmail;
String chatPartnerName = userRepository.findUserByEmail(chatPartnerEmail).orElseThrow(
UserNotFoundException::new).getName();

String currentAt = "";
List<String> currentAtByChatRoomId = chatRepository.findCurrentAtByChatRoomId(id);
if (currentAtByChatRoomId.isEmpty()) {
currentAt = null;
} else {
currentAt = currentAtByChatRoomId.get(0);
}

ChatRoomRes response = new ChatRoomRes(id, productId, productTitle, productLocation, currentAt, productPrice, productThumbnail, chatPartnerName);
chatRoomResponse.add(response);
if (results.hasContent()) {
return results.getContent().stream()
.map(result -> mapToChatRoomRes(result, userEmail))
.collect(Collectors.toList());
} else {
return Collections.emptyList(); // 채팅 리스트가 없는 경우 빈 배열을 반환
}

return chatRoomResponse;
}

private ChatRoomRes mapToChatRoomRes(Object[] result, String userEmail) {
Long id = (Long) result[0];
Long productId = (Long) result[1];
String productTitle = (String) result[2];
String productLocation = (String) result[3];
int productPrice = (int) result[4];
String productThumbnail = (String) result[5];
String sellerEmail = (String) result[6];
String buyerEmail = (String) result[7];

String chatPartnerEmail = userEmail.equals(sellerEmail) ? buyerEmail : sellerEmail;
String chatPartnerName = userRepository.findUserByEmail(chatPartnerEmail)
.orElseThrow(UserNotFoundException::new)
.getName();

String currentAt = chatRepository.findCurrentAtByChatRoomId(id)
.stream()
.findFirst()
.orElse(null);

return ChatRoomRes.builder()
.id(id)
.productId(productId)
.productTitle(productTitle)
.productLocation(productLocation)
.currentChatAt(currentAt)
.productPrice(productPrice)
.productThumbnail(productThumbnail)
.chatPartnerName(chatPartnerName)
.build();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,15 @@
import com.teamjo.techeermarket.domain.chats.repository.ChatRepository;
import com.teamjo.techeermarket.domain.chats.repository.ChatRoomRepository;
import com.teamjo.techeermarket.domain.products.entity.Products;
import com.teamjo.techeermarket.domain.products.mapper.ProductMapper;
import com.teamjo.techeermarket.domain.products.repository.ProductRepository;
import com.teamjo.techeermarket.global.exception.product.ProductNotFoundException;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.teamjo.techeermarket.global.exception.chat.ChatNotFoundException;

@Service
@RequiredArgsConstructor
Expand All @@ -24,10 +27,13 @@ public class ChatService {
private final ProductRepository productRepository;
private final ChatRepository chatRepository;
private final ChatMapper chatMapper;
private final ProductMapper productMapper;

@Transactional
public void saveMessage(ChatReq chatReq) {
ChatRoom chatRoom = chatRoomRepository.findById(chatReq.getChatRoomId()).orElseThrow();

ChatRoom chatRoom = chatRoomRepository.findById(chatReq.getChatRoomId())
.orElseThrow(ChatNotFoundException::new);

Chat chat = chatMapper.toEntity(chatRoom, chatReq.getSenderEmail(), chatReq.getMessage());

Expand All @@ -36,24 +42,25 @@ public void saveMessage(ChatReq chatReq) {

@Transactional(readOnly = true)
public ChatRes getMessage(Long chatRoomId) {
// DB 조회 (채팅 리스트, 제품)
List<Chat> chatList = chatRepository.findByChatRoomId(chatRoomId);
Long productId = chatRoomRepository.findById(chatRoomId).get().getProducts().getId();
Products products = productRepository.findById(productId).get();
ChatRes chatRes = new ChatRes();

ChatRoom chatRoom = chatRoomRepository.findById(chatRoomId)
.orElseThrow(ChatNotFoundException::new);
Long productId = chatRoom.getId();

Products products = productRepository.findById(productId)
.orElseThrow(ProductNotFoundException::new);

// 반환값 제작 (채팅 기록, 제품 정보, 첫 채팅 시각)
List<ChatInfo> response = chatList.stream()
.map(chatMapper::toChatResDtoList)
.collect(Collectors.toList());

ProductInfo productInfo = chatMapper.toProductInfo(products);

String chatCreateAt = chatRepository.findCreateAtByChatRoomId(chatRoomId).get(0);

chatRes.setChatInfoList(response);
chatRes.setProductInfo(productInfo);
chatRes.setChatCreateAt(chatCreateAt);
ProductInfo productInfo = productMapper.toProductInfo(products);

String chatCreateAt = chatList.get(chatList.size() - 1).getCreatedAt();

return chatRes;
return chatMapper.toChatResDto(response, productInfo, chatCreateAt);
}
}
Loading

0 comments on commit 7d25fbb

Please sign in to comment.