in src/cartservice/src/cartstore/AlloyDBCartStore.cs [62:94]
public async Task AddItemAsync(string userId, string productId, int quantity)
{
Console.WriteLine($"AddItemAsync for {userId} called");
try
{
await using var dataSource = NpgsqlDataSource.Create(connectionString);
// Fetch the current quantity for our userId/productId tuple
var fetchCmd = $"SELECT quantity FROM {tableName} WHERE userID='{userId}' AND productID='{productId}'";
var currentQuantity = 0;
var cmdRead = dataSource.CreateCommand(fetchCmd);
await using (var reader = await cmdRead.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
currentQuantity += reader.GetInt32(0);
}
var totalQuantity = quantity + currentQuantity;
var insertCmd = $"INSERT INTO {tableName} (userId, productId, quantity) VALUES ('{userId}', '{productId}', {totalQuantity})";
await using (var cmdInsert = dataSource.CreateCommand(insertCmd))
{
await Task.Run(() =>
{
return cmdInsert.ExecuteNonQueryAsync();
});
}
}
catch (Exception ex)
{
throw new RpcException(
new Status(StatusCode.FailedPrecondition, $"Can't access cart storage at {connectionString}. {ex}"));
}
}