Adding Items to a Cart
Learn how to add the functionality of adding items to the cart.
We'll cover the following...
How to add items to a cart
With these building blocks, it’s time to load up the cart. This is fundamental to any e-commerce system, so let’s get it right.
What are we trying to achieve?
-
We need to retrieve the current cart. If none exists, we need to create one.
-
If the item is already in the cart, we increment its quantity. If not, we add a new entry.
-
We need to save the updated cart.
To get this cart moving, we need to code the add/{itemId}
operation that we called in the inventory table:
@GetMappingMono<Rendering> home() {...}@PostMapping("/add/{id}") // <1>Mono<String> addToCart(@PathVariable String id) { // <2>return this.cartRepository.findById("My Cart").defaultIfEmpty(new Cart("My Cart")) // <3>.flatMap(cart -> cart.getCartItems().stream() // <4>.filter(cartItem -> cartItem.getItem().getId().equals(id)).findAny().map(cartItem -> {cartItem.increment();return Mono.just(cart);}).orElseGet(() -> { // <5>return this.itemRepository.findById(id).map(item -> new CartItem(item)).map(cartItem -> {cart.getCartItems().add(cartItem);return cart;});})).flatMap(cart -> this.cartRepository.save(cart)) // <6>.thenReturn("redirect:/"); // <7>}
Adding an Item to the Cart
Wow! That’s a lot of code. Let’s explore ...