실무 프로젝트로 배우는 Kotlin & Spring/이슈 관리 서비스 개발하기

코멘트 수정/ 코멘트 삭제

webmaster 2022. 11. 27. 23:22
728x90

코멘트 수정

Controller

@PutMapping("/{id}")
fun edit(
    authUser: AuthUser,
    @PathVariable id: Long,
    @RequestBody request: CommentRequest,
) = commentService.edit(id, authUser.userId, request)

Service

@Transactional
fun edit(id: Long, userId: Long, request: CommentRequest): CommentResponse? {
    return commentRepository.findByIdAndUserId(id, userId)?.run {
        body = request.body
        commentRepository.save(this).toResponse()
    }
}
  • 다른 사람의 댓글을 수정하면 안 되기 때문에 id와 userId를 통해 조회해 오는 메서드를 만들었다(SpringDataJPA에서 메서드 명을 보고 쿼리를 만들어 준다.)

Repository

interface CommentRepository : JpaRepository<Comment, Long> {
    fun findByIdAndUserId(id: Long, userId: Long): Comment?
}

코멘트 삭제

Controller

@DeleteMapping("/{id}")
@ResponseStatus(NO_CONTENT)
fun delete(
    authUser: AuthUser,
    @PathVariable issueId: Long,
    @PathVariable id: Long,
) {
    commentService.delete(issueId, id, authUser.userId)
}

Service


@Transactional
fun delete(issueId: Long, id: Long, userId: Long) {
    val issue =
        issueRepository.findByIdOrNull(issueId) ?: throw NotFoundException("이슈가 존재하지 않습니다.")
    commentRepository.findByIdAndUserId(id, userId)
        ?.let { comment -> issue.comments.remove(comment) }
}
  • JPA에서 List에 값을 삭제 하면 실제 Delete 쿼리가 나가는 기능을 활용해 데이터를 삭제한다.
728x90