Retructured solution
This commit is contained in:
+32
@@ -0,0 +1,32 @@
|
||||
using LiteCharms.Features.Shop.Postgres;
|
||||
|
||||
namespace LiteCharms.Features.ShoppingCarts.Commands.Handlers;
|
||||
|
||||
public class EmptyShoppingCartCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<EmptyShoppingCartCommand, Result>
|
||||
{
|
||||
public async ValueTask<Result> Handle(EmptyShoppingCartCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
if (!await context.ShoppingCarts.AnyAsync(c => c.Id == request.ShoppingCartId, cancellationToken))
|
||||
return Result.Fail($"Shopping could not be found with id {request.ShoppingCartId}");
|
||||
|
||||
if (await context.ShoppingCartItems.CountAsync(i => i.ShoppingCartId == request.ShoppingCartId, cancellationToken) == 0)
|
||||
return Result.Ok();
|
||||
|
||||
var cartItems = await context.ShoppingCartItems.Where(i => i.ShoppingCartId == request.ShoppingCartId).ToListAsync(cancellationToken);
|
||||
|
||||
context.RemoveRange(cartItems);
|
||||
|
||||
return await context.SaveChangesAsync(cancellationToken) > 0
|
||||
? Result.Ok()
|
||||
: Result.Fail($"Could not empty cart with id {request.ShoppingCartId}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user