public async Task<ServiceResponse<List<CartProductResponse>>> StoreCartItems(List<CartItem> cartItems)
{
cartItems.ForEach(cartItem => cartItem.UserId = GetUserId());
// Get Stored Cart Items for the User
var cartItemsFromDB = await _context.CartItems
.Where(ci => ci.UserId == GetUserId())
.ToListAsync();
// If the locally stored cartItem is equal to the DB stored items then update quantity
// otherwise add the cartItem to the DB
foreach (var cartItem in cartItems)
{
var sameItem = cartItemsFromDB.Find(dbItem => dbItem.ProductId == cartItem.ProductId
&& dbItem.ProductTypeId == cartItem.ProductTypeId);
if (sameItem != null){
sameItem.Quantity += cartItem.Quantity;
// Update Existing item quantity
_context.CartItems.Update(sameItem);
}
else
{
// Add the new item to the DB
_context.CartItems.Add(cartItem);
}
}
await _context.SaveChangesAsync();
return await GetDbCartProducts();
}