Implemented shopping carts functionality elements
This commit is contained in:
+32
@@ -0,0 +1,32 @@
|
||||
using LiteCharms.Infrastructure.Database;
|
||||
|
||||
namespace LiteCharms.Features.ShoppingCarts.Commands.Handlers;
|
||||
|
||||
public class UpdateShoppingCartItemCommandHandler(IDbContextFactory<LeadGeneratorDbContext> contextFactory) : IRequestHandler<UpdateShoppingCartItemCommand, Result>
|
||||
{
|
||||
public async ValueTask<Result> Handle(UpdateShoppingCartItemCommand 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 could not be found with id {request.ShoppingCartId}");
|
||||
|
||||
var item = await context.ShoppingCartItems.FirstOrDefaultAsync(i => i.ShoppingCartId == request.ShoppingCartId, cancellationToken);
|
||||
|
||||
if(item is null)
|
||||
return Result.Fail($"Shopping cart item could not be found with id {request.ShoppingCartItemId}");
|
||||
|
||||
item.Quantity = request.Quantity;
|
||||
|
||||
return await context.SaveChangesAsync(cancellationToken) > 0
|
||||
? Result.Ok()
|
||||
: Result.Fail($"Failed to update cart item quntity");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user