[인스타그램 클론코딩] 10. 게시물 댓글 기능 구현(Back-End)

2023. 2. 7. 10:28·Web/인스타 클론 코딩

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
'Web/인스타 클론 코딩' 카테고리의 다른 글
  • [인스타그램 클론코딩] 11. 프로필 수정 기능 구현(Back-End)
  • [인스타그램 클론코딩] 10. 게시물 댓글 기능 구현(Front-End)
  • [인스타그램 클론코딩] 09. 게시물 좋아요 기능 구현(Front-End)
  • [인스타그램 클론코딩] 09. 게시물 좋아요 기능 구현(Back-End)
뚝딱뚝딱2
뚝딱뚝딱2
  • 뚝딱뚝딱2
    개발도상국
    뚝딱뚝딱2
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 공부
        • Java
        • Spring Boot
        • LORA
      • Web
        • 인스타 클론 코딩
        • GPT 응답 API 서버
        • Spring Boot 예외 처리
        • 코테 준비용 서비스 만들기
      • DevOps
        • 쿠버네티스
        • 서버 만들기
      • 코딩테스트
        • 알고리즘
      • 교육
        • 스파르타코딩클럽 - 내일배움단
        • 혼자 공부하는 컴퓨터 구조 운영체제
      • 잡다한것
  • 블로그 메뉴

    • 홈
  • 링크

    • GITHUB
  • 공지사항

  • 인기 글

  • 태그

    react
    Entity
    스프링부트
    클러스터
    리액트
    mapstruct
    MSA
    백준
    spring boot
    인스타그램
    chat GPT
    티스토리챌린지
    Java
    OpenAI API
    예외
    스프링 부트
    오블완
    쿠버네티스
    클론코딩
    REST API
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
뚝딱뚝딱2
[인스타그램 클론코딩] 10. 게시물 댓글 기능 구현(Back-End)
상단으로

티스토리툴바