Search⌘ K
AI Features

Adding Items to a Cart

Explore how to add items to a shopping cart in a reactive Spring Boot application. Understand retrieving or creating carts, updating item quantities, and saving data efficiently with MongoDB and Java's Stream API.

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:

Java
@GetMapping
Mono<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 the key parts.

  1. In line 5, @PostMapping maps this method onto POST /add/{id}. This lets the web page put a button on every item.

  2. In line 6, @PathVariable extracts the {id} part of the route into the method parameter named id.

  3. In line 8, there’s that Reactor Recipe again! Find ...