Added package management
This commit is contained in:
+39
@@ -0,0 +1,39 @@
|
||||
using LiteCharms.Infrastructure.Database;
|
||||
|
||||
namespace LiteCharms.Features.ShoppingCarts.Commands.Handlers;
|
||||
|
||||
public class AddPackageToShoppingCartCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<AddPackageToShoppingCartCommand, Result>
|
||||
{
|
||||
public async ValueTask<Result> Handle(AddPackageToShoppingCartCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
if (!await context.Packages.AnyAsync(p => p.Id == request.PackageId, cancellationToken))
|
||||
return Result.Fail($"Package cold not be found by ID {request.PackageId}");
|
||||
|
||||
var shoppingCart = await context.ShoppingCarts.FirstOrDefaultAsync(c => c.Id == request.ShoppingCartId, cancellationToken);
|
||||
|
||||
if (shoppingCart is null)
|
||||
return Result.Fail($"Shopping cart could not be found by ID {request.ShoppingCartId}");
|
||||
|
||||
if (!await context.ShoppingCartPackages.AnyAsync(cp => cp.ShoppingCartId == request.ShoppingCartId, cancellationToken))
|
||||
return Result.Fail($"Package {request.PackageId} is already in the cart");
|
||||
|
||||
var newShoppingCartPackage = context.ShoppingCartPackages.Add(new Entities.ShoppingCartPackage
|
||||
{
|
||||
ShoppingCartId = request.ShoppingCartId,
|
||||
PackageId = request.PackageId
|
||||
});
|
||||
|
||||
return await context.SaveChangesAsync(cancellationToken) > 0
|
||||
? Result.Ok()
|
||||
: Result.Fail($"Could not add package of id {request.PackageId} to shopping cart {request.ShoppingCartId}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user