Skip to content

Commit 6e0a17a

Browse files
committed
feat: 댓글 삭제 API 구현
1 parent 8dc3335 commit 6e0a17a

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

src/main/java/com/example/log4u/domain/comment/controller/CommentController.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,12 @@ public ResponseEntity<CommentCreateResponseDto> addComment(@RequestBody @Valid C
3131
CommentCreateResponseDto response = commentService.addComment(userId, requestDto);
3232
return ResponseEntity.ok(response);
3333
}
34+
35+
@DeleteMapping("/{commentId}")
36+
public ResponseEntity<Void> deleteComment(@PathVariable Long commentId) {
37+
Long userId = 1L; //임시 처리
38+
39+
commentService.deleteComment(userId, commentId);
40+
return ResponseEntity.noContent().build();
41+
}
3442
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package com.example.log4u.domain.comment.exception;
2+
3+
public class UnauthorizedAccessException extends CommentException {
4+
public UnauthorizedAccessException() {
5+
super(CommentErrorCode.UNAUTHORIZED_COMMENT_ACCESS);
6+
}
7+
}

src/main/java/com/example/log4u/domain/comment/service/CommentService.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,33 @@ public class CommentService {
2020
private final CommentRepository commentRepository;
2121
private final DiaryService diaryService;
2222

23+
@Transactional
2324
public CommentCreateResponseDto addComment(Long userId, CommentCreateRequestDto requestDto) {
2425
checkDiaryExists(requestDto);
2526
Comment comment = requestDto.toEntity(userId);
2627
commentRepository.save(comment);
2728
return CommentCreateResponseDto.of(comment);
2829
}
2930

31+
@Transactional
32+
public void deleteComment(Long userId, Long commentId) {
33+
Comment comment = getComment(commentId);
34+
validateCommentOwner(userId, comment);
35+
commentRepository.delete(comment);
36+
}
37+
3038
private void checkDiaryExists(CommentCreateRequestDto requestDto) {
3139
diaryService.checkDiaryExists(requestDto.diaryId());
3240
}
41+
42+
private void validateCommentOwner(Long userId, Comment comment) {
43+
if (!comment.getUserId().equals(userId)) {
44+
throw new UnauthorizedAccessException();
45+
}
46+
}
47+
48+
private Comment getComment(Long commentId) {
49+
return commentRepository.findById(commentId)
50+
.orElseThrow(NotFoundCommentException::new);
51+
}
3352
}

0 commit comments

Comments
 (0)