Skip to content

Commit

Permalink
#22 [feat] 댓글 삭제 로직 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
sohyundoh committed Jan 7, 2024
1 parent f937bf6 commit b62759e
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.mile.comment.repository;

import com.mile.comment.domain.Comment;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface CommentRepository extends JpaRepository<Comment, Long> {

@Query("select c.user.id from Comment c where c = :comment")
Long findUserIdByComment(@Param(value = "comment") final Comment comment);
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,49 @@
package com.mile.comment.service;

import com.mile.comment.domain.Comment;
import com.mile.comment.repository.CommentRepository;
import com.mile.exception.message.ErrorMessage;
import com.mile.exception.model.ForbiddenException;
import com.mile.exception.model.NotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class CommentService {

private final CommentRepository commentRepository;

@Transactional
public void deleteComment(
final Long commentId,
final Long userId
) {
Comment comment = findById(commentId);
authenticateUser(comment, userId);
delete(comment);
}

private void delete(
final Comment comment
) {
commentRepository.delete(comment);
}
private Comment findById(
final Long commentId
) {
return commentRepository.findById(commentId)
.orElseThrow(
() -> new NotFoundException(ErrorMessage.COMMENT_NOT_FOUND)
);
}
private void authenticateUser(
final Comment comment,
final Long userId
) {
if(!commentRepository.findUserIdByComment(comment).equals(userId)) {
throw new ForbiddenException(ErrorMessage.COMMENT_ACCESS_ERROR);
}
}
}

0 comments on commit b62759e

Please sign in to comment.