Skip to content

Commit

Permalink
Increment the number of products in cart if they already exist upon c…
Browse files Browse the repository at this point in the history
…reation
  • Loading branch information
badass-techie committed Oct 28, 2023
1 parent 491c9cf commit 8bb80da
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ public void save(CartItem cartItem, Long userId) {
redisTemplate.opsForHash().put(userId.toString(), cartItem.getProductId(), cartItem);
}

public CartItem findByUserIdAndProductId(Long userId, String productId) {
return (CartItem)redisTemplate.opsForHash().get(userId.toString(), productId);
}

public List<CartItem> findAllByUserId(Long userId) {
return redisTemplate.opsForHash().values(userId.toString()).stream()
.map(cartItem -> (CartItem) cartItem)
Expand Down
22 changes: 14 additions & 8 deletions Cart/src/main/java/com/badasstechie/cart/service/CartService.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,21 @@ public CartResponse mapCartItemsToResponse(List<CartItem> cartItems){
}

public CartResponse addToCart(CartItemRequest cartItemRequest, Long userId) {
CartItem cartItem = CartItem.builder()
.productId(cartItemRequest.productId())
.productName(cartItemRequest.productName())
.unitPrice(cartItemRequest.unitPrice())
.quantity(cartItemRequest.quantity())
.build();
if (cartItemRepository.findByUserIdAndProductId(userId, cartItemRequest.productId()) == null) {
CartItem cartItem = CartItem.builder()
.productId(cartItemRequest.productId())
.productName(cartItemRequest.productName())
.unitPrice(cartItemRequest.unitPrice())
.quantity(cartItemRequest.quantity())
.build();

cartItemRepository.save(cartItem, userId);
return getCartItems(userId);
cartItemRepository.save(cartItem, userId);
return getCartItems(userId);
}
else {
// if product already in cart increment by 1
return incrementQuantity(userId, cartItemRequest.productId());
}
}

public CartResponse getCartItems(Long userId) {
Expand Down

0 comments on commit 8bb80da

Please sign in to comment.