33 lines
1.3 KiB
C#
33 lines
1.3 KiB
C#
using LiteCharms.Infrastructure.Database;
|
|
|
|
namespace LiteCharms.Features.ShoppingCarts.Commands.Handlers;
|
|
|
|
public class UpdateShoppingCartItemCommandHandler(IDbContextFactory<ShopDbContext> 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));
|
|
}
|
|
}
|
|
}
|