in src/cart/src/cartstore/ValkeyCartStore.cs [122:170]
public async Task AddItemAsync(string userId, string productId, int quantity)
{
var stopwatch = Stopwatch.StartNew();
_logger.LogInformation("AddItemAsync called with userId={userId}, productId={productId}, quantity={quantity}", userId, productId, quantity);
try
{
EnsureRedisConnected();
var db = _redis.GetDatabase();
// Access the cart from the cache
var value = await db.HashGetAsync(userId, CartFieldName);
Oteldemo.Cart cart;
if (value.IsNull)
{
cart = new Oteldemo.Cart
{
UserId = userId
};
cart.Items.Add(new Oteldemo.CartItem { ProductId = productId, Quantity = quantity });
}
else
{
cart = Oteldemo.Cart.Parser.ParseFrom(value);
var existingItem = cart.Items.SingleOrDefault(i => i.ProductId == productId);
if (existingItem == null)
{
cart.Items.Add(new Oteldemo.CartItem { ProductId = productId, Quantity = quantity });
}
else
{
existingItem.Quantity += quantity;
}
}
await db.HashSetAsync(userId, new[]{ new HashEntry(CartFieldName, cart.ToByteArray()) });
await db.KeyExpireAsync(userId, TimeSpan.FromMinutes(60));
}
catch (Exception ex)
{
throw new RpcException(new Status(StatusCode.FailedPrecondition, $"Can't access cart storage. {ex}"));
}
finally
{
addItemHistogram.Record(stopwatch.ElapsedTicks);
}
}