Added package management
This commit is contained in:
+35
@@ -0,0 +1,35 @@
|
||||
using LiteCharms.Infrastructure.Database;
|
||||
|
||||
namespace LiteCharms.Features.ShoppingCarts.Commands.Handlers;
|
||||
|
||||
public class RemovePackageFromShoppingCartCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<RemovePackageFromShoppingCartCommand, Result>
|
||||
{
|
||||
public async ValueTask<Result> Handle(RemovePackageFromShoppingCartCommand 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 cart could not be found by ID {request.ShoppingCartId}");
|
||||
|
||||
if (!await context.ShoppingCartPackages.AnyAsync(p => p.Id == request.ShoppingCartPackageId, cancellationToken))
|
||||
return Result.Fail($"Shopping cart package {request.ShoppingCartPackageId} is not in the shopping cart {request.ShoppingCartId}");
|
||||
|
||||
var shoppingCartPackage = await context.ShoppingCartPackages.FirstOrDefaultAsync(cp => cp.Id == request.ShoppingCartPackageId, cancellationToken);
|
||||
|
||||
if (shoppingCartPackage is null)
|
||||
return Result.Ok();
|
||||
|
||||
context.ShoppingCartPackages.Remove(shoppingCartPackage!);
|
||||
|
||||
return await context.SaveChangesAsync(cancellationToken) > 0
|
||||
? Result.Ok()
|
||||
: Result.Fail($"Could remove package of id {request.ShoppingCartPackageId} from shopping cart {request.ShoppingCartId}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user