33 lines
1.4 KiB
C#
33 lines
1.4 KiB
C#
using LiteCharms.Extensions;
|
|
using LiteCharms.Infrastructure.Database;
|
|
using LiteCharms.Models;
|
|
|
|
namespace LiteCharms.Features.ShoppingCarts.Queries.Handlers;
|
|
|
|
public class GetShoppingCartPackagesQueryHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<GetShoppingCartPackagesQuery, Result<ShoppingCartPackage[]>>
|
|
{
|
|
public async ValueTask<Result<ShoppingCartPackage[]>> Handle(GetShoppingCartPackagesQuery 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}");
|
|
|
|
var packages = await context.ShoppingCartPackages.AsNoTracking()
|
|
.OrderByDescending(o => o.CreatedAt)
|
|
.Where(cp => cp.ShoppingCartId == request.ShoppingCartId)
|
|
.ToArrayAsync(cancellationToken);
|
|
|
|
return packages?.Length > 0
|
|
? Result.Ok(packages.Select(p => p.ToModel()).ToArray())
|
|
: Result.Fail($"Could not find packaged in shopping cart by ID {request.ShoppingCartId}");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return Result.Fail<ShoppingCartPackage[]>(new Error(ex.Message).CausedBy(ex));
|
|
}
|
|
}
|
|
}
|