Files
components/LiteCharms.Features/Shop/ShoppingCarts/Queries/Handlers/GetCustomerShoppingCartsQueryHandler.cs
T
2026-05-13 20:06:24 +02:00

31 lines
1.4 KiB
C#

using LiteCharms.Extensions;
using LiteCharms.Features.Shop.Postgres;
using LiteCharms.Features.Shop.ShoppingCarts.Models;
using LiteCharms.Features.ShoppingCarts.Queries;
namespace LiteCharms.Features.ShoppingCarts.Queries.Handlers;
public class GetCustomerShoppingCartsQueryHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<GetCustomerShoppingCartsQuery, Result<ShoppingCart[]>>
{
public async ValueTask<Result<ShoppingCart[]>> Handle(GetCustomerShoppingCartsQuery request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (!await context.Customers.AnyAsync(c => c.Id == request.CustomerId, cancellationToken))
return Result.Fail<ShoppingCart[]>(new Error($"Customer with Id {request.CustomerId} does not exist."));
var shoppingCarts = await context.ShoppingCarts.Where(sc => sc.CustomerId == request.CustomerId).ToArrayAsync(cancellationToken);
return shoppingCarts?.Length > 0
? Result.Ok(shoppingCarts.Select(c => c.ToModel()).ToArray())
: Result.Fail<ShoppingCart[]>(new Error($"No shopping carts found for customer with Id {request.CustomerId}."));
}
catch (Exception ex)
{
return Result.Fail<ShoppingCart[]>(new Error(ex.Message).CausedBy(ex));
}
}
}