public async Task <IActionResult> Handle(Request request, CancellationToken cancellationToken = default) { if (request is null) { return(BadRequest()); } DiagnosticsContext.Set("CartId", request.CartId); DiagnosticsContext.Set("ProductId", request.ProductId); DiagnosticsContext.Set("Increment", request.Increment); CartEntity cart = await Context.Carts.AsNoTracking().SingleOrDefaultAsync(c => c.Id == request.CartId, cancellationToken); if (cart is null) { Logger.LogTrace("Cart not found"); string message = Localizer.GetStringSafe("CartNotFound", request.CartId); return(NotFoundProblem(message)); } ItemEntity item = await Context.Items.AsTracking().SingleOrDefaultAsync(c => c.CartId == request.CartId && c.ProductId == request.ProductId, cancellationToken); if (item is null) { item = Mapper.Map <ItemEntity>(request); item.CreatedOn = Clock.UtcNow; item.ModifiedOn = Clock.UtcNow; DiagnosticsContext.Set("NewQuantity", item.Quantity); DiagnosticsContext.Set("PreviousQuantity", 0); Context.Items.Add(item); } else { int existingQuantity = item.Quantity; item.Quantity += request.Increment; item.ModifiedOn = Clock.UtcNow; DiagnosticsContext.Set("NewQuantity", item.Quantity); DiagnosticsContext.Set("PreviousQuantity", existingQuantity); } await Context.SaveChangesAsync(cancellationToken); var response = Mapper.Map <Response>(item); return(Ok(response)); }
public async Task <IActionResult> Handle(CancellationToken cancellationToken = default) { CartEntity cart = new() { CreatedOn = Clock.UtcNow }; Context.Add(cart); await Context.SaveChangesAsync(cancellationToken); DiagnosticsContext.Set("CartId", cart.Id); return(CreatedAtAction(nameof(GetCartById.Handle), nameof(GetCartById), new { cart.Id }, cart)); } }
public async Task <IActionResult> Handle(Guid id, CancellationToken cancellationToken = default) { DiagnosticsContext.Set("CartId", id); CartEntity cart = await Context.Carts.AsNoTracking().SingleOrDefaultAsync(c => c.Id == id, cancellationToken); if (cart is null) { Logger.LogTrace("Cart not found"); string message = Localizer.GetStringSafe("CartNotFound", id); return(NotFoundProblem(message)); } ItemEntity[] items = await Context.Items.AsNoTracking().Where(i => i.CartId == cart.Id).ToArrayAsync(cancellationToken); var response = Mapper.Map <Response>(cart); response.Items = items; DiagnosticsContext.Set("CartItemCount", items.Length); return(Ok(response)); }