-
-
Save dcomartin/80a653825d773b9f6244652b0949eadf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ShoppingCartRepository | |
{ | |
private readonly IDbConnection _connection; | |
public ShoppingCartRepository(IDbConnection connection) | |
{ | |
_connection = connection; | |
} | |
public async Task<ShoppingCartEventDomain> GetShoppingCart(Guid shoppingCartId) | |
{ | |
var shoppingCart = await _connection.QueryFirstAsync<ShoppingCart>("SELECT CustomerId FROM ShoppingCarts WHERE ShoppingCartId=@ShopingCartId", | |
new {ShoppingCartId = shoppingCartId}); | |
var items = await _connection.QueryAsync<ShoppingCartItem>("SELECT ProductId, Quantity FROM ShoppingCartItems WHERE ShoppingCartId=@ShopingCartId", | |
new {ShoppingCartId = shoppingCartId}); | |
shoppingCart.Items = items.ToList(); | |
return new ShoppingCartEventDomain(shoppingCart); | |
} | |
public async Task Save(ShoppingCartEventDomain shoppingCart) | |
{ | |
var trx = _connection.BeginTransaction(); | |
var evnts = shoppingCart.GetEvents(); | |
foreach (var evnt in evnts) | |
{ | |
if (evnt is ItemAdded itemAdded) | |
{ | |
await ItemAdded(itemAdded, trx); | |
} | |
else if (evnt is QuantityIncremented quantityIncremented) | |
{ | |
await QuantityIncremented(quantityIncremented, trx); | |
} | |
else if (evnt is ItemRemoved itemRemoved) | |
{ | |
await ItemRemoved(itemRemoved, trx); | |
} | |
} | |
trx.Commit(); | |
} | |
private async Task ItemAdded(ItemAdded evnt, IDbTransaction trx) | |
{ | |
await _connection.ExecuteAsync("INSERT INTO ShoppingCartItems (ShoppingCartId, ProductId, Quantity, Price) VALUES (@ShoppingCartId, @ProductId, @Quantity, @Price)", | |
new | |
{ | |
ShoppingCartId = evnt.ShoppingCartId, | |
ProductID = evnt.ProductId, | |
Quantity = evnt.Quantity, | |
Price = evnt.Price | |
}, trx); | |
} | |
private async Task QuantityIncremented(QuantityIncremented evnt, IDbTransaction trx) | |
{ | |
await _connection.ExecuteAsync("UPDATE ShoppingCartItems SET Quantity=Quantity+@Quantity WHERE ShoppingCartId=@ShoppingCartId AND ProductID=@ProductId", | |
new | |
{ | |
ShoppingCartId = evnt.ShoppingCartId, | |
ProductID = evnt.ProductId, | |
Quantity = evnt.Quantity, | |
}, trx); | |
} | |
private async Task ItemRemoved(ItemRemoved evnt, IDbTransaction trx) | |
{ | |
await _connection.ExecuteAsync("DELETE FROM ShoppingCartItems WHERE ShoppingCartId=@ShoppingCartId AND ProductId=@ProductId", | |
new | |
{ | |
ShoppingCartId = evnt.ShoppingCartId, | |
ProductID = evnt.ProductId | |
}, trx); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment