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
'실무 프로젝트로 배우는 Kotlin & Spring > 이슈 관리 서비스 개발하기' 카테고리의 다른 글
| 코멘트 등록 (0) | 2022.11.27 |
|---|---|
| 이슈 수정 / 이슈 삭제 (0) | 2022.11.27 |
| 이슈 목록 조회/ 이슈 상세 조회 (0) | 2022.11.27 |
| 이슈 등록 (0) | 2022.11.27 |
| 공통 에러 처리 (0) | 2022.11.26 |