1. PostChat Entity와 PostChatRepository 생성
@Entity
@Data
@NoArgsConstructor
public class PostChat extends BaseTimeEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "post_chat_id")
private Long id;
@ManyToOne
@JoinColumn(name = "post_id")
private Post post;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
private String content;
@Builder
public PostChat(Post post, User user, String content) {
this.post = post;
this.user = user;
this.content = content;
}
}
public interface PostChatRepository extends JpaRepository<PostChat, Long> {
List<PostChat> findAllByPostOrderByCreatedDateDesc(Post post);
}
- PostChat 테이블에는 어떤 포스트에 작성된 댓글인지 알 수 있는, post_id 컬럼과 누가썼는지 알 수 있는 user_id 컬럼 그리고 어떤 내용인지 알수 있는 content 컬럼과 함께 생성된 날짜를 알 수 있는 BaseTimeEntity 객체를 상속받는다.
- PostChatRepository에서는 해당 게시글 댓글을 최근 시간순으로 불러오는 메서드를 작성해 주었다.
2. PostChat 관련 Dto 생성
@Data
public class PostChatDto {
private Long chatId;
private String email;
private String nickname;
private String profileUrl;
private String content;
private LocalDateTime createdDate;
@Builder
public PostChatDto(Long chatId, String email, String nickname, String profileUrl, String content, LocalDateTime createdDate) {
this.chatId = chatId;
this.email = email;
this.nickname = nickname;
this.profileUrl = profileUrl;
this.content = content;
this.createdDate = createdDate;
}
public static PostChatDto toDto(PostChat postChat) {
return PostChatDto.builder()
.chatId(postChat.getId())
.email(postChat.getUser().getEmail())
.nickname(postChat.getUser().getNickname())
.profileUrl(postChat.getUser().getProfileImgUrl())
.content(postChat.getContent())
.createdDate(postChat.getCreatedDate())
.build();
}
}
@Data
public class PostChatRequestDto {
private Long postId;
private String content;
@Builder
public PostChatRequestDto(Long postId, String content) {
this.postId = postId;
this.content = content;
}
}
@Data
public class PostChatResponseDto {
private List<PostChatDto> postChatList;
@Builder
public PostChatResponseDto(List<PostChatDto> postChatList) {
this.postChatList = postChatList;
}
}
- PostChatRequestDto는 댓글 입력시 받는 요청에 대한 Dto이며 postId와 내용을 전달받는다.
- PostChatResponseDto는 해당 게시글의 모든 댓글에 대한 내용을 넘겨줄 Dto 이며 PostChatDto의 리스트이다.
- PostChatDto는 해당 댓글에 대한 정보를 넘겨받는 Dto 이다. chatId, email, nickname, profileUrl, content, createdDate를 가지고 있으며 toDto 메서드를 통해 postChat엔티티에서 Dto로 전환할 수 있도록 만들어 주었다.
3. PostService에 채팅 기능 로직 작성
@Transactional
public PostChatResponseDto getPostChatList(Long postId) {
Post post = postRepository.findById(postId).orElseThrow(() -> new EntityNotFoundException("해당 게시글을 찾을 수 없습니다."));
List<PostChat> postChatList = postChatRepository.findAllByPostOrderByCreatedDateDesc(post);
List<PostChatDto> postChatDtoList = new ArrayList<>();
postChatList.forEach((postChat -> {
postChatDtoList.add(PostChatDto.toDto(postChat));
}));
return PostChatResponseDto.builder().postChatList(postChatDtoList).build();
}
@Transactional
public PostChatResponseDto setPostChat(User user, PostChatRequestDto requestDto) {
Post post = postRepository.findById(requestDto.getPostId()).orElseThrow(() -> new EntityNotFoundException("해당 게시글을 찾을 수 없습니다."));
postChatRepository.save(PostChat.builder()
.post(post)
.user(user)
.content(requestDto.getContent())
.build());
return this.getPostChatList(requestDto.getPostId());
}
@Transactional
public PostChatResponseDto deletePostChat(Long postId, Long postChatId) {
PostChat postChat = postChatRepository.findById(postChatId).orElseThrow(() -> new EntityNotFoundException("해당 댓글을 찾을 수 없습니다."));
postChatRepository.delete(postChat);
return this.getPostChatList(postId);
}
- getPostChatList는 해당 게시글에 대한 모든 댓글을 반환해주는 로직이다.
- setPostChat은 해당 게시글에 넘겨받은 정보로 댓글을 입력하는 로직이다.
- deletePostChat은 해당 게시글의 특정 댓글을 삭제하는 로직이다.
4. PostController 수정
@GetMapping("/posts/chat")
public ResponseEntity getPostChatList(@RequestParam(value = "postId") Long postId) {
try {
return ResponseEntity.ok().body(postService.getPostChatList(postId));
} catch (Exception e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}
@PostMapping("/posts/chat")
public ResponseEntity setPostChat(@CurrentUser User user, @RequestBody PostChatRequestDto requestDto) {
try {
return ResponseEntity.ok().body(postService.setPostChat(user, requestDto));
} catch (Exception e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}
@DeleteMapping("/posts/chat")
public ResponseEntity deletePostChat(@RequestParam(value = "postId") Long postId, @RequestParam(value = "chatId") Long chatId) {
try {
return ResponseEntity.ok().body(postService.deletePostChat(postId, chatId));
} catch (Exception e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}
- 각자 해당 Url에 대한 postService를 매핑해주기 위해 작성하였다.
'Web > 인스타 클론 코딩' 카테고리의 다른 글
[인스타그램 클론코딩] 11. 프로필 수정 기능 구현(Back-End) (0) | 2023.02.07 |
---|---|
[인스타그램 클론코딩] 10. 게시물 댓글 기능 구현(Front-End) (0) | 2023.02.07 |
[인스타그램 클론코딩] 09. 게시물 좋아요 기능 구현(Front-End) (0) | 2023.02.04 |
[인스타그램 클론코딩] 09. 게시물 좋아요 기능 구현(Back-End) (0) | 2023.02.04 |
[인스타그램 클론코딩] 08. 홈 화면 구현(Front-End) (0) | 2023.02.03 |