Skip to content

Comment

HifumiAlice edited this page Jun 10, 2024 · 5 revisions

Comment에서는 Todo의 댓글 생성, 수정, 삭제를 합니다.


목차

전체Code

생성하기

수정하기

삭제하기


Code

CommentController
    @RequestMapping("/todos/{id}")
    @RestController
    class CommentController(private val commentService: CommentService) {
    
        @PostMapping()
        fun createComment(
            @PathVariable id: Long,
            @RequestBody request: CommentCreateRequest,
            @AuthenticationPrincipal member: MemberDetails?
        ): ResponseEntity<CommentResponse> {
            return ResponseEntity.status(HttpStatus.CREATED).body(commentService.createComment(id, request, member))
        }
    
        @PutMapping("/{comment-id}")
        fun updateComment(
            @PathVariable id: Long,
            @PathVariable(name = "comment-id") commentId: Long,
            @RequestBody request: CommentUpdateRequest,
            @AuthenticationPrincipal member: MemberDetails?
        ): ResponseEntity<CommentResponse> {
            return ResponseEntity.status(HttpStatus.OK).body(commentService.updateComment(id, commentId, request, member))
        }
    
        @DeleteMapping("/{comment-id}")
        fun deleteComment(
            @PathVariable id: Long, @PathVariable(name = "comment-id") commentId: Long,
            @AuthenticationPrincipal member: MemberDetails?
        ): ResponseEntity<Unit> {
            return ResponseEntity.status(HttpStatus.OK).body(commentService.deleteComment(id, commentId, member))
        }
    
    }
CommentService
@Service
class CommentServiceImpl(
    private val todoRepository: TodoRepository,
    private val commentRepository: CommentRepository,
    private val memberRepository: MemberRepository
) : CommentService {

    @PreAuthorize("hasRole('USER')")
    @Transactional
    override fun createComment(
        id: Long,
        request: CommentCreateRequest,
        memberDetails: MemberDetails?
    ): CommentResponse {

        memberDetails ?: throw UnAuthorizedException()

        val todo: Todo = todoRepository.findByIdOrNull(id) ?: throw ModelNotFoundException("todo", id)
        val member: Member =
            memberRepository.findByIdOrNull(memberDetails.id) ?: throw ModelNotFoundException(
                "member",
                memberDetails.id
            )

        val comment: Comment = Comment(
            comment = request.comment,
            memberId = memberDetails.id
        )

        todo.addComment(comment)
        commentRepository.save(comment)

        return comment.toResponse(member)
    }

    @PreAuthorize("hasRole('USER')")
    @Transactional
    override fun updateComment(
        id: Long,
        commentId: Long,
        request: CommentUpdateRequest,
        memberDetails: MemberDetails?
    ): CommentResponse {

        memberDetails ?: throw UnAuthorizedException()

        val todo: Todo = todoRepository.findByIdOrNull(id) ?: throw ModelNotFoundException("todo", id)
        val comment: Comment =
            commentRepository.findByIdOrNull(commentId) ?: throw ModelNotFoundException("comment", commentId)
        val member: Member =
            memberRepository.findByIdOrNull(memberDetails.id) ?: throw ModelNotFoundException(
                "member",
                memberDetails.id
            )

        val isCommentBelongTodo: (it: Comment) -> Boolean = { it -> it == comment }

        todo.comments.find(isCommentBelongTodo) ?: throw IllegalStateException("Todo doesn't have comment")

        if (memberDetails.id != comment.memberId)
            throw UnAuthorizedException()

        comment.comment = request.comment
        commentRepository.save(comment)

        return comment.toResponse(member)
    }

    @PreAuthorize("hasRole('USER')")
    @Transactional
    override fun deleteComment(id: Long, commentId: Long, memberDetails: MemberDetails?): Unit {

        memberDetails ?: throw UnAuthorizedException()

        val todo: Todo = todoRepository.findByIdOrNull(id) ?: throw ModelNotFoundException("todo", id)
        val comment: Comment =
            commentRepository.findByIdOrNull(commentId) ?: throw ModelNotFoundException("comment", commentId)

        todo.comments.find { it == comment } ?: throw IllegalStateException("Todo doesn't have comment")


        if (memberDetails.id != comment.memberId)
            throw UnAuthorizedException()

        todo.removeComment(comment)
        todoRepository.save(todo)

    }
}
Comment
@Entity
@Table(name = "comment")
class Comment(

    @Column(name = "comment", nullable = false)
    var comment: String,

    @Column(name = "member_id", nullable = false)
    val memberId: Long,

    @Column(name = "created_at", nullable = false)
    val createdAt: LocalDateTime = LocalDateTime.now(),
) {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long? = null
}

fun Comment.toResponse(member: Member): CommentResponse {
    return CommentResponse(
        id = id!!,
        comment = comment,
        createdAt = createdAt,
        member = member.toResponse()
    )
}
CommentResponse
data class CommentResponse(
    val id: Long,
    val comment: String,
    val createdAt: LocalDateTime,
    val member: MemberResponse 
)

생성하기

CommentController
@PostMapping()
fun createComment(
    @PathVariable id: Long,
    @RequestBody request: CommentCreateRequest,
    @AuthenticationPrincipal member: MemberDetails?
): ResponseEntity<CommentResponse> {
    return ResponseEntity.status(HttpStatus.CREATED).body(commentService.createComment(id, request, member))
}
CommentService
@PreAuthorize("hasRole('USER')")
@Transactional
override fun createComment(
    id: Long,
    request: CommentCreateRequest,
    memberDetails: MemberDetails?
): CommentResponse {

    memberDetails ?: throw UnAuthorizedException()

    val todo: Todo = todoRepository.findByIdOrNull(id) ?: throw ModelNotFoundException("todo", id)
    val member: Member =
        memberRepository.findByIdOrNull(memberDetails.id) ?: throw ModelNotFoundException(
            "member",
            memberDetails.id
        )

    val comment: Comment = Comment(
        comment = request.comment,
        memberId = memberDetails.id
    )

    todo.addComment(comment)
    commentRepository.save(comment)

    return comment.toResponse(member)
}
CommentCreateRequest
data class CommentCreateRequest (
    val comment : String
)
  • Todo id를 입력받습니다. --> id에 해당하는 Todo가 없으면 에러 메시지를 반환합니다.
  • 로그인 한 사용자의 정보를 가져와서 댓글을 생성하고 CommentResponse를 반환합니다.

수정하기

CommentController
@PutMapping("/{comment-id}")
fun updateComment(
    @PathVariable id: Long,
    @PathVariable(name = "comment-id") commentId: Long,
    @RequestBody request: CommentUpdateRequest,
    @AuthenticationPrincipal member: MemberDetails?
): ResponseEntity<CommentResponse> {
    return ResponseEntity.status(HttpStatus.OK).body(commentService.updateComment(id, commentId, request, member))
}
CommentService
@PreAuthorize("hasRole('USER')")
@Transactional
override fun updateComment(
    id: Long,
    commentId: Long,
    request: CommentUpdateRequest,
    memberDetails: MemberDetails?
): CommentResponse {

    memberDetails ?: throw UnAuthorizedException()

    val todo: Todo = todoRepository.findByIdOrNull(id) ?: throw ModelNotFoundException("todo", id)
    val comment: Comment =
        commentRepository.findByIdOrNull(commentId) ?: throw ModelNotFoundException("comment", commentId)
    val member: Member =
        memberRepository.findByIdOrNull(memberDetails.id) ?: throw ModelNotFoundException(
            "member",
            memberDetails.id
        )

    val isCommentBelongTodo: (it: Comment) -> Boolean = { it -> it == comment }

    todo.comments.find(isCommentBelongTodo) ?: throw IllegalStateException("Todo doesn't have comment")

    if (memberDetails.id != comment.memberId)
        throw UnAuthorizedException()

    comment.comment = request.comment
    commentRepository.save(comment)

    return comment.toResponse(member)
}
CommentUpdateRequest
data class CommentUpdateRequest (
    val comment : String
)
  • Todo와 Comment의 id를 받아서 Todo가 존재하는지 Comment가 존재하는지와 Todo안에 Comment가 존재하는지 확인합니다.
  • 만약 3가지가 전부 만족하지 못하면 에러 메시지를 반환합니다.
  • 로그인 한 사용자가 댓글 작성자와 다르다면 에러 메시지를 반환합니다.
  • 위 과정을 모두 만족하면 댓글 내용을 수정 후 CommentResponse를 반환합니다.

삭제하기

CommentController
@DeleteMapping("/{comment-id}")
fun deleteComment(
    @PathVariable id: Long, @PathVariable(name = "comment-id") commentId: Long,
    @AuthenticationPrincipal member: MemberDetails?
): ResponseEntity<Unit> {
    return ResponseEntity.status(HttpStatus.OK).body(commentService.deleteComment(id, commentId, member))
}
CommentService
@PreAuthorize("hasRole('USER')")
@Transactional
override fun deleteComment(id: Long, commentId: Long, memberDetails: MemberDetails?): Unit {

    memberDetails ?: throw UnAuthorizedException()

    val todo: Todo = todoRepository.findByIdOrNull(id) ?: throw ModelNotFoundException("todo", id)
    val comment: Comment =
        commentRepository.findByIdOrNull(commentId) ?: throw ModelNotFoundException("comment", commentId)

    todo.comments.find { it == comment } ?: throw IllegalStateException("Todo doesn't have comment")


    if (memberDetails.id != comment.memberId)
        throw UnAuthorizedException()

    todo.removeComment(comment)
    todoRepository.save(todo)

}
  • Todo와 Comment id를 받아서 각각 존재하는지 확인 후 Todo 안에 Comment가 있는지 확인합니다.
  • 만약 한 가지라도 만족 하지 못 한다면 에러 메시지를 반환합니다.
  • 로그인 한 사용자가 댓글 작성자와 다르면 에러 메시지를 반환합니다.
  • 모든 과정이 성공하면 댓글을 삭제하고 CommentResponse를 반환합니다.

Clone this wiki locally