Implemented shopping carts functionality elements

This commit is contained in:
Khwezi Mngoma
2026-05-06 10:48:02 +02:00
parent 83f51c6a23
commit 4321b03735
13 changed files with 341 additions and 5 deletions
@@ -0,0 +1,18 @@
using LiteCharms.Models;
namespace LiteCharms.Features.ShoppingCarts.Queries;
public class GetShoppingCartItemsQuery : IRequest<Result<ShoppingCartItem[]>>
{
public Guid ShoppingCartId { get; set; }
private GetShoppingCartItemsQuery(Guid shoppingCartId) => ShoppingCartId = shoppingCartId;
public static GetShoppingCartItemsQuery Create(Guid shoppingCartId)
{
if (shoppingCartId == Guid.Empty)
throw new ArgumentException("Shopping cart id is required", nameof(shoppingCartId));
return new(shoppingCartId);
}
}
@@ -0,0 +1,30 @@
using LiteCharms.Extensions;
using LiteCharms.Infrastructure.Database;
using LiteCharms.Models;
namespace LiteCharms.Features.ShoppingCarts.Queries.Handlers;
public class GetShoppingCartItemsQueryHandler(IDbContextFactory<LeadGeneratorDbContext> contextFactory) : IRequestHandler<GetShoppingCartItemsQuery, Result<ShoppingCartItem[]>>
{
public async ValueTask<Result<ShoppingCartItem[]>> Handle(GetShoppingCartItemsQuery request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (!await context.ShoppingCarts.AnyAsync(i => i.Id == request.ShoppingCartId, cancellationToken))
return Result.Fail($"Shopping cart could not be found with id {request.ShoppingCartId}");
var items = await context.ShoppingCartItems.AsNoTracking()
.Where(i => i.ShoppingCartId == request.ShoppingCartId).ToArrayAsync(cancellationToken);
return items?.Length > 0
? Result.Ok(items.Select(i => i.ToModel()).ToArray())
: Result.Fail<ShoppingCartItem[]>($"Failed to retrieve shopping cart items with id {request.ShoppingCartId}");
}
catch (Exception ex)
{
return Result.Fail<ShoppingCartItem[]>(new Error(ex.Message).CausedBy(ex));
}
}
}