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:
Wow! That’s a lot of code. Let’s explore the key parts.
-
In line 5,
@PostMappingmaps this method ontoPOST /add/{id}. This lets the web page put a button on every item. -
In line 6,
@PathVariableextracts the{id}part of the route into the method parameter namedid. -
In line 8, there’s that Reactor Recipe again! Find ...