Implemented shopping carts functionality elements
This commit is contained in:
+40
@@ -0,0 +1,40 @@
|
||||
using LiteCharms.Infrastructure.Database;
|
||||
|
||||
namespace LiteCharms.Features.ShoppingCarts.Commands.Handlers;
|
||||
|
||||
public class AddItemToShoppingCartCommandHandler(IDbContextFactory<LeadGeneratorDbContext> contextFactory) : IRequestHandler<AddItemToShoppingCartCommand, Result>
|
||||
{
|
||||
public async ValueTask<Result> Handle(AddItemToShoppingCartCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
if (!await context.ProductPrices.AnyAsync(c => c.Id == request.ProductPriceId, cancellationToken))
|
||||
return Result.Fail($"Product item could not be found with id {request.ProductPriceId}");
|
||||
|
||||
var cart = await context.ShoppingCarts.FirstOrDefaultAsync(c => c.Id == request.ShoppingCartId, cancellationToken);
|
||||
|
||||
if (cart is null)
|
||||
return Result.Fail($"Shopping cart could not be found with id {request.ShoppingCartId}");
|
||||
|
||||
if (cart.ShoppingCartItems?.Any(i => i.ProductPriceId == request.ProductPriceId) == true)
|
||||
return Result.Fail($"Item already in shopping cart with id {request.ShoppingCartId}");
|
||||
|
||||
context.ShoppingCartItems.Add(new Entities.ShoppingCartItem
|
||||
{
|
||||
ShoppingCartId = request.ShoppingCartId,
|
||||
ProductPriceId = request.ProductPriceId,
|
||||
Quantity = request.Quantity
|
||||
});
|
||||
|
||||
return await context.SaveChangesAsync(cancellationToken) > 0
|
||||
? Result.Ok()
|
||||
: Result.Fail($"Failed to add cart item with id {request.ProductPriceId}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user