Files
components/LiteCharms.Features/CartPackages/Commands/Handlers/DeletePackageItemsCommandHandler.cs
T
2026-05-10 14:18:56 +02:00

30 lines
1.2 KiB
C#

using LiteCharms.Infrastructure.Database;
namespace LiteCharms.Features.CartPackages.Commands.Handlers;
public class DeletePackageItemsCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<DeletePackageItemsCommand, Result>
{
public async ValueTask<Result> Handle(DeletePackageItemsCommand 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($"Could not find package by ID {request.PackageId}");
var items = await context.PackageItems.Where(i => i.PackageId == request.PackageId).ToArrayAsync(cancellationToken);
context.PackageItems.RemoveRange(items);
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok()
: Result.Fail($"Failed to delete package {request.PackageId} items");
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
}