오늘 Codekata는 2문제를 풀었다.
첫 번째 문제는 어제 풀다가 미루었던 문제였는데, Disjoint-set으로 풀려고 시도했다가 틀렸다는 결과를 얻고 자신의 풀이가 아니라는 과정을 거쳐서, 그제야 단순히 dfs + bruteforce로 해결할 수 있는 것을 깨달았다. 그렇게 많은 시간을 소비했던 문제가 생각 외로 단순한 문제라서 다소 허무해졌다.
계속해서 어제 해결 못한 인가 문제를 해결했다, 사실 해결 자체는 단순했는데, Authority의 이름이 틀렸다. 그러니까, 권한 이름이, USER가 아닌, ROLE_USER라서 문제가 발생했던 것이였다. 어쨌든 단순해서 금방 해결하고 Cart 기능을 구현하였다.
Cart는 (아이템, 유저, 양)으로 이루어진 데이터베이스를 활용한다. 유저의 장바구니에 있는 내용을 가져올 때엔 유저의 id로 repository에서 list로 가져오는 방식으로 구현을 하였다.
override fun getCart(): List<CartResponse> {
return cartRepository.findByUserId(SecurityUtil.getLoginUserId()!!).map { CartResponse.from(it) }
}
그리고 단순하지만 null이 아닌 경우를 Kotlin식으로 하는 방법을 검색해서 이를 처음으로 적용해 보았다.
mutableProperty?.also { doSomething(it) } ?: doOtherThing()
이런 방식인데, doSomething()은 null이 아니면 실행되고, doOtherThing()은 null일 때 실행된다. 이를 적용해서.
@Transactional
override fun addItemInCart(cartAddRequest: CartAddRequest): CartResponse {
val product = productRepository.findProductById(cartAddRequest.productId)
?: throw ModelNotFoundException("Product", cartAddRequest.productId)
if(!product.availability) throw IllegalArgumentException("해당 제품을 이용할 수 없습니다.")
val user = userRepository.findByIdOrNull(SecurityUtil.getLoginUserId())
?: throw ModelNotFoundException("User", SecurityUtil.getLoginUserId())
val cart = CartResponse.from(
cartRepository.findByUserIdAndProductId(SecurityUtil.getLoginUserId()!!, cartAddRequest.productId)
?.also { cart -> cart.apply { cart.quantity += cartAddRequest.quantity } } ?: cartRepository.save(
Cart(
user = user,
product = product,
quantity = cartAddRequest.quantity
))
)
if(cart.quantity >= product.quantity)
throw IllegalArgumentException("${product.itemName}을 ${cartAddRequest.quantity}만큼 넣을 수 없습니다.")
return cart
}
이렇게, 구현을 해보았다.
Cart를 구현할 때, QueryDSL이 아닌, JPQL을 사용했는데, delete를 하는 함수에서 에러가 발생했다. 찾아본 결과, @Query를 사용해서 insert, delete, update 등의 작업을 하면 @Modifying을 추가적으로 붙여줘야한다는 사실을 알 게 되었다. 생각을 해보면 그동안 JPQL을 Select로만 사용을 했어서 delete 같은 DML은 처음 썼었다. 그래서 붙이고 나서야 오류를 해결할 수 있었다.
@Modifying
@Query("delete from Cart c where c.user.id = :userId")
fun deleteAllByUserId(userId: Long)
내일은 EC2를 통한 배포를 시도해보자.
'부트캠프 일지' 카테고리의 다른 글
부트캠프 43일차 후기 (0) | 2024.01.26 |
---|---|
부트캠프 42일차 후기 (1) | 2024.01.25 |
부트캠프 40일차 후기 (1) | 2024.01.23 |
부트캠프 39일차 후기 (1) | 2024.01.22 |
부트캠프 38일차 후기 (0) | 2024.01.19 |