오늘은 복습 과제를 했다
인증/인가, CRUD를 작업하였다
처음에는 기본 CRUD로 시작하였다
시작은 순조로웠다
잘하고 싶은 마음에 저번 팀 프로젝트에서 코드를 가져와 그대로 썼다
@Transactional
fun createComment(postId: Long, request: CommentRequest): CommentResponse {
val member = memberService.getMember()
if (!commentRepository.existsByPostIdAndMemberId(postId, member.id))
throw IllegalArgumentException("Post with id $postId does not exist")
return postService.getPostEntity(postId)
.let { commentRepository.save(toEntity(it, request, member.id)).toResponse(member.name) }
}
@Transactional
fun updateComment(
postId: Long,
commentId: Long,
request: CommentRequest
): CommentResponse {
return commentRepository.findByIdOrNull(commentId)
?.let {
if (!memberService.matchMemberId(it.memberId))
throw IllegalArgumentException("MemberInfo do not match")
it.content = request.content
it.toResponse(memberService.getMember().name)
} ?: throw ModelNotFoundException("updateComment", commentId)
}
@Transactional
fun deleteComment(postId: Long, commentId: Long) {
return commentRepository.findByIdOrNull(commentId)
?.let {
if (!memberService.matchMemberId(it.memberId))
throw IllegalArgumentException("MemberInfo do not match")
commentRepository.deleteById(commentId)
} ?: throw ModelNotFoundException("updateComment", commentId)
}
}
이런 코드들과
fun getMemberIdFromToken(): Long? {
val authentication = SecurityContextHolder.getContext().authentication
if (authentication == null || authentication.principal !is MemberPrincipal) {
throw UnauthorizedException("Invalid authentication")
}
val principal = authentication.principal as MemberPrincipal
return principal.id
}
fun matchMemberId(memberId: Long): Boolean { // Token의 ID와 파라미터ID를 비교
return getMemberIdFromToken() == memberId
}
이런 이해도 안 되는 코드들을 썼다
결과는 오류투성이였다
빈을 생성할 수 없다는 오류가 생기고
이유 모를 오류도 생겼다
그러다 팀원에게 도움을 청했는데
이렇게 이해도 안 되는 코드 그냥 가져다 쓰면 지금은 모르겠지만 나중에는 낭패를 본다고....
맞는 말이다
내 수준에 맞지 않는 코드를 써봤자 이해가 안 되니 내 것이 될 수 없다
그래서 하던 프로젝트를 삭제하고 내가 이해할 수 있고 직접 코드로 옮길 수 있는 것들로 다시 만들기로 했다
그래서 나온 것들이
@Service
class PostService(
private val postRepository: PostRepository
) {
fun getPostList(): List<PostResponse> {
return postRepository.findAll().map { it.toPostResponse() }
}
fun getPost(postId: Long): PostResponse {
return postRepository.findByIdOrNull(postId)?.toPostResponse() ?: throw RuntimeException("Post not found")
}
@Transactional
fun createPost(request: CreatePostRequest): PostResponse {
return postRepository.save(
Post(
title = request.title,
content = request.content
)
).toPostResponse()
}
@Transactional
fun updatePost(postId: Long, request: UpdatePostRequest): PostResponse {
val result = postRepository.findByIdOrNull(postId) ?: throw RuntimeException("Post not found")
result.title = request.title
result.content = request.content
return postRepository.save(result).toPostResponse()
}
@Transactional
fun deletePost(postId: Long) {
val result = postRepository.findByIdOrNull(postId) ?: throw RuntimeException("Post not found")
return postRepository.delete(result)
}
}
이런 코드
@Service
class CommentService(
private val commentRepository: CommentRepository
) {
fun getCommentList(): List<CommentResponse> {
return commentRepository.findAll().map { it.toCommentResponse() }
}
fun getComment(commentId: Long): CommentResponse {
return commentRepository.findByIdOrNull(commentId)?.toCommentResponse()
?: throw RuntimeException("Comment not found")
}
@Transactional
fun createComment(request: CommentRequest): CommentResponse {
return commentRepository.save(
Comment(
content = request.content
)
).toCommentResponse()
}
@Transactional
fun updateComment(commentId: Long, request: CommentRequest): CommentResponse {
val result = commentRepository.findByIdOrNull(commentId) ?: throw RuntimeException("Comment not found")
result.content = request.content
return commentRepository.save(result).toCommentResponse()
}
@Transactional
fun deleteComment(commentId: Long) {
val result = commentRepository.findByIdOrNull(commentId) ?: throw RuntimeException("Comment not found")
return commentRepository.delete(result)
}
}
이런 코드들이다
아직 구현 단계라서 안 들어간 부분들이 많지만 마음으로는 한결 가벼워졌다
내가 이해할 수 있고 내가 구현할 수 있는 부분에서 최대한 간결하게 코드를 짜는 것이 이번 과제의 목표이다
실력이 생각보다 많이 늘어 자만했다
앞으로 자만하지 않고 겸손한 자세로 배움에 임할 것이다
'잘하고 있어 나 자신!!' 카테고리의 다른 글
2024.06.18 (화) 프로젝트 회고 (0) | 2024.06.18 |
---|---|
2024.06.11 (화) 프로젝트 시작 (0) | 2024.06.11 |
2024.06.03 (월) 팀 프로젝트 회고 (0) | 2024.06.03 |