berryberrybin / board-project

0 stars 0 forks source link

삭제 - delete, deleteById, remove #9

Open berryberrybin opened 1 year ago

berryberrybin commented 1 year ago

delete

// CommentLikeService.java
public void cancelCommentLike(CommentCommand.CancelCommentLikeCommand cancelCommentLikeCommand) {
    User user = getUserById(cancelCommentLikeCommand.getUserId());
    Comment comment = getCommentById(cancelCommentLikeCommand.getCommentId());

    CommentLike commentLike = getCommentLike(user, comment);
    commentLikeRepository.delete(commentLike);
}

private User getUserById(UUID userId) {
    return userRepository.findById(userId)
        .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND, "user.byId", List.of(userId.toString())));
}

private Comment getCommentById(UUID commentId) {
    return commentRepository.findById(commentId)
        .orElseThrow(
            () -> new BusinessException(ErrorCode.NOT_FOUND, "comment.byId", List.of(commentId.toString())));
}
private CommentLike getCommentLike(User user, Comment comment) {
    return commentLikeRepository.findByUserAndComment(user, comment)
        .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND, "commentLike", null));
}

remove

// PostCommandService.java
public void cancelLikePost(PostCommand.CancelLikePostCommand cancelLikePostCommand) {
    UUID userId = cancelLikePostCommand.getUserId();
    UUID postId = cancelLikePostCommand.getPostId();

    Post post = postRepository.findById(postId)
        .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND, "post.byId", List.of(postId.toString())));

    PostLike postLike = postLikeRepository.findByUserIdAndPostId(userId, postId)
        .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND, "postLike", null));

    post.cancelLike(postLike);
}
// Post.java
@Getter
@Entity
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Post extends DateTimeEntity {

    @Id
    @GeneratedValue(generator = "UUID")
    @Column(name = "post_id", columnDefinition = "BINARY(16)")
    @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
    private UUID id;

    @ManyToOne
    @JoinColumn(name = "board_id")
    private Board board;

    @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<PostLike> likes = new ArrayList<>();

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    private String title;

    private String description;

    @Builder
    public Post(Board board, User user, String title, String description) {
        this.board = board;
        this.user = user;
        this.title = title;
        this.description = description;
    }

    public Integer getLikeCount() {
        return likes.size();
    }

    public void addLike(PostLike postLike) {
        this.likes.add(postLike);
    }

    public void cancelLike(PostLike like) {
        this.likes.remove(like);
    }
}
berryberrybin commented 1 year ago