Retructured solution
This commit is contained in:
+36
@@ -0,0 +1,36 @@
|
||||
using LiteCharms.Features.Shop.Postgres;
|
||||
|
||||
namespace LiteCharms.Features.ShoppingCarts.Commands.Handlers;
|
||||
|
||||
public class RemoveShoppingCartItemCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<RemoveShoppingCartItemCommand, Result>
|
||||
{
|
||||
public async ValueTask<Result> Handle(RemoveShoppingCartItemCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
if (!await context.ProductPrices.AnyAsync(c => c.Id == request.ShoppingCartItemId, cancellationToken))
|
||||
return Result.Fail($"Product item could not be found with id {request.ShoppingCartItemId}");
|
||||
|
||||
var cart = await context.ShoppingCarts.FirstOrDefaultAsync(c => c.Id == request.ShoppingCartId, cancellationToken);
|
||||
|
||||
if (cart is null)
|
||||
return Result.Fail($"Shopping cart item could not be found with id {request.ShoppingCartId}");
|
||||
|
||||
var item = await context.ShoppingCartItems.FirstOrDefaultAsync(i => i.Id == request.ShoppingCartItemId, cancellationToken);
|
||||
|
||||
if (item is null) return Result.Ok();
|
||||
|
||||
context.ShoppingCartItems.Remove(item);
|
||||
|
||||
return await context.SaveChangesAsync(cancellationToken) > 0
|
||||
? Result.Ok()
|
||||
: Result.Fail($"Failed to remove shopping cart item with id {request.ShoppingCartItemId}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user