enhance shopping-cart logic
This commit is contained in:
@@ -5,6 +5,7 @@ import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface ShoppingCartRepository extends JpaRepository<ShoppingCart, Long> {
|
||||
@@ -12,4 +13,6 @@ public interface ShoppingCartRepository extends JpaRepository<ShoppingCart, Long
|
||||
public List<ShoppingCart> findAllByOwner_ID(long id);
|
||||
|
||||
public List<ShoppingCart> removeByOwner_ID(long id);
|
||||
|
||||
public Optional<ShoppingCart> findByOwnerIDAndProductID(long ownerID, long productID);
|
||||
}
|
||||
|
||||
@@ -26,6 +26,15 @@ public class ShoppingCartService {
|
||||
if (productOptional.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
// cart item already exists
|
||||
var cartExist = shoppingCartRepository.findByOwnerIDAndProductID(user.getID(), productID);
|
||||
if (cartExist.isPresent()) {
|
||||
var cart = cartExist.get();
|
||||
cart.setCount(cart.getCount() + 1);
|
||||
shoppingCartRepository.save(cart);
|
||||
return true;
|
||||
}
|
||||
// item not exist, create a new one
|
||||
var product = productOptional.get();
|
||||
ShoppingCart shoppingCart = new ShoppingCart();
|
||||
shoppingCart.setCount(count);
|
||||
|
||||
Reference in New Issue
Block a user