본문 바로가기

항해99

23.10.09 항해 99 16기 실전 프로젝트 5일차

오늘 공부한 것

* 실전 프로젝트 댓글 및 대댓글기능 코드 정리 및 Postman Test

 

오늘은 지난번에 작성한 댓글과 대댓글 기능을 Postman으로 Test 하면서

코드 정리를 했다

다행히 구현한 모든 기능이 잘 동작했다

내일은 댓글에 대한 페이징 기능을 구현해보려고한다

 

수정한 코드는 아래와 같다

 

1. 댓글

 1) Controller

@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class CommentsController {
    private final CommentsService commentsService;

    // 댓글 생성
    @PostMapping("/posts/{postId}/comments")
    public ResponseEntity<MessageResponseDto> commentsCreate(@PathVariable("postId") Long postId,
                                                              @RequestBody CommentsRequestDto requestDto,
                                                              @AuthenticationPrincipal UserDetailsImpl userDetails) {
        return ResponseEntity.ok(commentsService.commentsCreate(postId, requestDto, userDetails.getUsers()));
    }

    // 댓글 조회
    @GetMapping("/posts/{postId}/comments")
    public ResponseEntity<List<CommentsResponseDto>> commentsList(@PathVariable("postId") Long postId) {
        return ResponseEntity.ok(commentsService.commentsList(postId));
    }

    // 댓글 수정
    @PutMapping("/comments/{commentId}")
    public ResponseEntity<MessageResponseDto> commentsUpdate( @PathVariable("commentId") Long commentId,
                                                              @RequestBody CommentsRequestDto request,
                                                              @AuthenticationPrincipal UserDetailsImpl userDetails) {
       return ResponseEntity.ok(commentsService.commentsUpdate( commentId, request, userDetails.getUsers()));
    }

    // 댓글 삭제
    @DeleteMapping("/comments/{commentId}")
    public ResponseEntity<MessageResponseDto> commentsDelete(@PathVariable("commentId") Long commentId,
                                                             @AuthenticationPrincipal UserDetailsImpl userDetails) {
        return ResponseEntity.ok(commentsService.commentsDelete(commentId, userDetails.getUsers()));
    }
}

 

  2) Dto

@Getter
public class CommentsRequestDto {
    private String contents;
}
@Getter
public class CommentsResponseDto {
    private Long commnetId;
    private String contents;
    private String nickname;
    private LocalDateTime createAt;
    private LocalDateTime modifiedAt;


    public CommentsResponseDto(Comments comments, String users) {
        this.commnetId = comments.getId();
        this.contents = comments.getContents();
        this.nickname = users;
        this.createAt = comments.getCreatedAt();
        this.modifiedAt = comments.getModifiedAt();

    }
}

 

  3) Entity

@Entity
@Getter
@NoArgsConstructor
@Table(name = "comments")
public class Comments extends TimeStamped {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name ="comments_id")
    private  Long id;

    private String nickname;

    @Column(nullable = false, length = 500)
    private String contents;

    @ManyToOne
    @JoinColumn(name = "posts_id")
    private Posts posts;

    @OneToMany (mappedBy = "comments", orphanRemoval = true)
    @OrderBy("createdAt asc")
    private List<Replies> repliesList= new ArrayList<>();


    public Comments(CommentsRequestDto requestDto, Users users, Posts posts) {
        this.nickname = users.getNickName();
        this.contents = requestDto.getContents();
        this.posts = posts;
    }

    public void update(CommentsRequestDto requestDto, Users users) {
        this.nickname = users.getNickName();
        this.contents = requestDto.getContents();
    }
}

 

  4) Repository

public interface CommentsRepository extends JpaRepository<Comments, Long> {

    List<Comments> findByPostsOrderByCreatedAtDesc(Posts posts);

    List<Comments> findByPosts(Posts posts);

    List<Comments> findByPosts_IdOrderByCreatedAtDesc(Long postId);

}

 

  5) Service

@Service
@RequiredArgsConstructor
public class CommentsService {
    private final CommentsRepository commentsRepository;
    private final PostsRepository postsRepository;

    // 댓글 생성
    public MessageResponseDto commentsCreate(Long postId,
                                              CommentsRequestDto requestDto,
                                              Users users) {

        Posts posts = postsRepository.findById(postId).orElseThrow(
                () -> new CustomException(ErrorCode.POST_NOT_EXIST)); // 존재하지 않는 게시글입니다

        Comments comments = new Comments(requestDto, users, posts);
        commentsRepository.save(comments);

        return new MessageResponseDto ("댓글을 작성하였습니다", 200);
    }

    // 댓글 조회
    public List<CommentsResponseDto> commentsList(Long postId) {
        List<Comments> commentsList = commentsRepository.findByPosts_IdOrderByCreatedAtDesc(postId);
        if (commentsList.isEmpty()) {
            throw new CustomException(ErrorCode.POST_NOT_EXIST); // 존재하지 않는 게시글입니다
        }

        List<CommentsResponseDto> commentsResponseDtoList = new ArrayList<>();

        for (Comments comments : commentsList) {
            commentsResponseDtoList.add(new CommentsResponseDto(comments, comments.getNickname()));
        }
        return commentsResponseDtoList;
    }

    // 댓글 수정
    @Transactional
    public MessageResponseDto commentsUpdate( Long commentId,
                                              CommentsRequestDto request,
                                              Users users) {
        Comments comments = findById(commentId);
        if (users.getUserRole() == UserRoleEnum.ADMIN) {
            comments.update(request, users);
            return new MessageResponseDto("관리자가 댓글을 수정하였습니다", 200);
        } else if (users.getNickName().equals(comments.getNickname())) {
                comments.update(request, users);
                return new MessageResponseDto("댓글을 수정하였습니다", 200);
            } else {
                throw new CustomException(ErrorCode.NOT_ALLOWED); // 권한이 없습니다
            }
        }

    // 댓글 삭제
    public MessageResponseDto commentsDelete(Long commentId,
                                             Users users) {

        Comments comments = findById(commentId);
        if (users.getUserRole() == UserRoleEnum.ADMIN) {
            commentsRepository.delete(comments);
                return new MessageResponseDto("관리자가 댓글을 삭제하였습니다", 200);
        } else if (users.getNickName().equals(comments.getNickname())) {
                commentsRepository.delete(comments);
                return new MessageResponseDto("댓글을 삭제하였습니다", 200);
            } else {
                throw new CustomException(ErrorCode.NOT_ALLOWED); // 권한이 없습니다
        }
    }

    private Comments findById(Long id) {
        return commentsRepository.findById(id).orElseThrow(
                () ->new CustomException(ErrorCode.COMMENTS_NOT_EXIST)); // 존재하지 않는 댓글입니다
    }
}

 

2. 대댓글

 1) Controller

@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class RepliesController {
    private final RepliesService repliesService;

    // 대댓글 생성
    @PostMapping("comments/{commentId}/replies")
    public ResponseEntity<MessageResponseDto> repliesCreate(@PathVariable("commentId") Long commentId,
                                                            @RequestBody RepliesRequestDto requestDto,
                                                            @AuthenticationPrincipal UserDetailsImpl userDetails) {
        return ResponseEntity.ok(repliesService.repliesCreate(commentId, requestDto, userDetails.getUsers()));
    }

    // 대댓글 조회
    @GetMapping("/comments/{commentId}/replies")
    public ResponseEntity<List<RepliesResponseDto>> repliesList(@PathVariable("commentId") Long commentId) {
        return ResponseEntity.ok(repliesService.repliesList(commentId));
    }

    // 대댓글 수정
    @PutMapping("replies/{repliesId}")
    public ResponseEntity<MessageResponseDto> repliesUpdate( @PathVariable("repliesId") Long repliesId,
                                                             @RequestBody RepliesRequestDto request,
                                                             @AuthenticationPrincipal UserDetailsImpl userDetails) {
        return ResponseEntity.ok(repliesService.repliesUpdate(repliesId, request, userDetails.getUsers()));
    }

    // 대댓글 삭제
    @DeleteMapping("replies/{repliesId}")
    public ResponseEntity<MessageResponseDto> repliesDelete(@PathVariable("repliesId") Long repliesId,
                                                            @AuthenticationPrincipal UserDetailsImpl userDetails) {
        return ResponseEntity.ok(repliesService.repliesDelete(repliesId, userDetails.getUsers()));
    }
}

 

  2) Dto

@Getter
public class RepliesRequestDto {
    private String contents;
}
@Getter
public class RepliesResponseDto {
    private Long repliesId;
    private String contents;
    private String nickname;
    private LocalDateTime createAt;
    private LocalDateTime modifiedAt;

    public RepliesResponseDto(Replies replies, String users) {
        this.repliesId = replies.getId();
        this.contents = replies.getContents();
        this.nickname = users;
        this.createAt = replies.getCreatedAt();
        this.modifiedAt = replies.getModifiedAt();
    }
}

  

  3) Entity

@Entity
@Getter
@NoArgsConstructor
@Table(name = "replies")
public class Replies extends TimeStamped {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name ="replies_id")
    private Long id;

    private String nickname;

    @Column(nullable = false, length = 500)
    private String contents;

    @ManyToOne
    @JoinColumn(name = "comments_id")
    private Comments comments;

    public Replies(RepliesRequestDto requestDto, Users users, Comments comments) {
        this.nickname = users.getNickName();
        this.contents = requestDto.getContents();
        this.comments = comments;
    }

    public void update(RepliesRequestDto requestDto, Users users) {
        this.nickname = users.getNickName();
        this.contents = requestDto.getContents();
    }
}

 

 4) Repository

public interface RepliesRepository extends JpaRepository<Replies, Long> {


    List<Replies> findAllByCommentsOrderByCreatedAtDesc(Comments comments);

    List<Replies> findByComments_IdOrderByCreatedAtDesc(Long commentId);
}

 

  5) Service

@Service
@RequiredArgsConstructor
public class RepliesService {
    private final RepliesRepository repliesRepository;
    private final CommentsRepository commentsRepository;


    // 대댓글 생성
    public MessageResponseDto repliesCreate(Long commentId,
                                            RepliesRequestDto requestDto,
                                            Users users) {

        Comments comments = commentsRepository.findById(commentId).orElseThrow(
                () -> new CustomException(ErrorCode.COMMENTS_NOT_EXIST)); // 존재하지 않는 댓글입니다

        Replies replies = new Replies(requestDto, users, comments);
        repliesRepository.save(replies);

        return new MessageResponseDto ("대댓글을 작성하였습니다", 200);
    }

    // 대댓글 조회
    public List<RepliesResponseDto> repliesList(Long commentId) {
        List<Replies> repliesList = repliesRepository.findByComments_IdOrderByCreatedAtDesc(commentId);
        if (repliesList.isEmpty()) {
            throw new CustomException(ErrorCode.COMMENTS_NOT_EXIST); // 존재하지 않는 댓글입니다
        }

        List<RepliesResponseDto> repliesResponseDtoList = new ArrayList<>();

        for (Replies replies : repliesList) {
            repliesResponseDtoList.add(new RepliesResponseDto(replies, replies.getNickname()));
        }
        return repliesResponseDtoList;
    }

    @Transactional
    // 대댓글 수정
    public MessageResponseDto repliesUpdate( Long repliesId,
                                             RepliesRequestDto request,
                                             Users users) {

        Replies replies = findById(repliesId);
        if (users.getUserRole() == UserRoleEnum.ADMIN) {
            replies.update(request, users);
            return new MessageResponseDto("관리자가 대댓글을 수정하였습니다", 200);
        } else if (users.getNickName().equals(replies.getNickname())) {
                replies.update(request, users);
                return new MessageResponseDto("대댓글을 수정하였습니다", 200);
            } else {
                throw new CustomException(ErrorCode.NOT_ALLOWED); // 권한이 없습니다
        }
    }


    // 대댓글 삭제
    public MessageResponseDto repliesDelete(Long repliesId,
                                            Users users) {

        Replies replies = findById(repliesId);
        if (users.getUserRole() == UserRoleEnum.ADMIN) {
            repliesRepository.delete(replies);
            return new MessageResponseDto("관리자가 대댓글을 삭제하였습니다", 200);
        } else if (users.getNickName().equals(replies.getNickname())) {
                repliesRepository.delete(replies);
                return new MessageResponseDto("대댓글을 삭제하였습니다", 200);
            } else {
                throw new CustomException(ErrorCode.NOT_ALLOWED); // 권한이 없습니다
        }
    }


    private Replies findById(Long id) {
        return repliesRepository.findById(id).orElseThrow(
                () -> new CustomException(ErrorCode.REPLIES_NOT_EXIST)); // 존재하지 않는 대댓글입니다
    }
}