Project

댓글 crud 코드

haedal-uni 2022. 6. 26. 18:46
728x90

 

CommentController

더보기

 

@RequiredArgsConstructor
@RestController
public class CommentController {
    private final CommentService commentService;

    // 댓글 저장
    @PostMapping("/comment")
    public Comment setComment(@ModelAttribute CommentDto commentDto) {
        return commentService.setComment(commentDto);
    }

    @GetMapping("/comment")
    public List<Comment> getComment(@RequestParam int idx){
        return commentService.getComment(idx);
    }

    // AuthenticationPrincipal : 로그인한 사용자의 정보를 파라메터로 받고 싶을때
    @PutMapping("/comment/{commentId}/registry/{registryId}")
    public Comment updateComment(@PathVariable Long commentId, @PathVariable int registryId,
                                 @RequestBody CommentDto commentDto,
                                 @AuthenticationPrincipal UserDetailsImpl userDetails) throws AccessDeniedException {
        return commentService.updateComment(commentId, registryId, commentDto, userDetails);
    }

    // 댓글 삭제
    @DeleteMapping("/comment/{commentId}/registry/{registryId}")
    public void deleteComment(@PathVariable Long commentId, @PathVariable int registryId,
                              @RequestBody CommentDto commentDto,
                              @AuthenticationPrincipal UserDetailsImpl userDetails)throws AccessDeniedException {
        commentService.deleteComment(commentId, registryId, commentDto, userDetails);
    }

    @GetMapping("/finduser")  // sessionStorage에 닉네임 값이 저장 안되어 있는 경우
    public String findUser(@AuthenticationPrincipal UserDetailsImpl userDetails) {
        return commentService.findUser(userDetails);
    }
}

 

 

CommentService

더보기

 

@RequiredArgsConstructor
@Service
public class CommentService {
    private final CommentRepository commentRepository;
    private final RegistryRepository registryRepository;

    @Transactional
    public Comment setComment(CommentDto commentDto) {
        Comment comment = new Comment(commentDto);
        commentRepository.save(comment);
        return comment;
    }

    public List<Comment> getComment(int idx){
        List<Comment> commentList = commentRepository.findAllByRegistryId(idx);
        return commentList;
    }

    @Transactional
    public Comment updateComment(Long commentId, int registryId, CommentDto commentDto, UserDetailsImpl userDetails) throws AccessDeniedException {
        registryRepository.findById((long) registryId).orElseThrow(
                () -> new NullPointerException("해당 게시글이 존재하지 않습니다.")
        );

        Comment comment = commentRepository.findById(commentId).orElseThrow(
                () -> new NullPointerException("해당 댓글이 존재하지 않습니다.")
        );

        if (!userDetails.getUser().getNickname().equals(comment.getNickname()) ) {
            throw new AccessDeniedException("권한이 없습니다.");
        }

        comment.setComment(commentDto.getComment());
        commentRepository.save(comment);
        return comment;

    }

    @Transactional
    public void deleteComment(Long commentId, int registryId, CommentDto commentDto, UserDetailsImpl userDetails) throws AccessDeniedException {
        registryRepository.findById((long) registryId).orElseThrow(
                () -> new NullPointerException("해당 게시글이 존재하지 않습니다.")
        );

        Comment comment = commentRepository.findById(commentId).orElseThrow(
                () -> new NullPointerException("해당 댓글이 존재하지 않습니다.")
        );

        if (!userDetails.getUser().getNickname().equals(comment.getNickname()) ) {
            throw new AccessDeniedException("권한이 없습니다.");
        }

        commentRepository.delete(comment);
    }
    // sessionStorage에 닉네임 값이 저장 안되어 있는 경우
    public String findUser(UserDetailsImpl userDetails) {
        return userDetails.getUser().getNickname();
    }

}

 

 

Comment

더보기

 

@Setter
@Getter
@NoArgsConstructor
@Entity
public class Comment extends Timestamped {
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    @Column(name = "COMMENT_ID")
    private Long idx;

    @Column(nullable = false)
    private String nickname;

    @Column(nullable = false)
    private String comment;

    @Column(nullable = false)
    private int registryId;

    public Comment(CommentDto commentDto) {
        this.nickname = commentDto.getNickname();
        this.comment = commentDto.getComment();
        this.registryId = commentDto.getRegistryId();
    }
}

 

 

CommentRepository

더보기

 

public interface CommentRepository extends JpaRepository<Comment, Long> {
    List<Comment> findAllByRegistryId(int idx);
}

 

 

CommentDto

더보기

 

@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class CommentDto {
    private String nickname;
    private String comment;
    private int registryId;
}
728x90

'Project' 카테고리의 다른 글

댓글 test 코드  (0) 2022.06.20
회원가입 코드  (0) 2022.06.19
로그인 코드  (0) 2022.06.18
웹소켓 - 상대방과 나 구분하기  (0) 2022.06.04
웹소켓 기본 코드  (0) 2022.06.03