Beispiel #1
0
        public async Task <bool> Handle(GetCartRequest request, IOutputPort <GetCartResponse> outputPort)
        {
            var linesDto = _cartService.Lines;

            if (!linesDto.Any())
            {
                outputPort.Handle(new GetCartResponse(null, 0, false, "Your Cart is Empty"));
                return(false);
            }
            var totalValue = await _cartService.ComputeTotalValue();

            outputPort.Handle(new GetCartResponse(linesDto, totalValue, true));
            return(true);
        }
        public override Task <Hipstershop.Cart> GetCart(GetCartRequest request, ServerCallContext context)
        {
            IIncomingRemoteCallTracer incomingRemoteCallTracer = getTracer(context, "GetCart");

            try {
                incomingRemoteCallTracer.Start();
                return(cartStore.GetCartAsync(request.UserId));
            } catch (Exception e) {
                Console.WriteLine(e.ToString());
                incomingRemoteCallTracer.Error(e);
            } finally {
                incomingRemoteCallTracer.End();
            }
            return(null);
        }
Beispiel #3
0
 public IHttpActionResult GetCart(GetCartRequest request)
 {
     try
     {
         if (!ModelState.IsValid)
         {
             string errorMsg = string.Empty;
             errorMsg += string.Join(" ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));
             return(BadRequest(errorMsg));
         }
         return(Ok(_shoppingCartModel.GetUserCart(request.UserId)));
     }
     catch (Exception ex)
     {
         return(BadRequest(ex.Message));
     }
 }
Beispiel #4
0
        public async Task AddItem_ItemExists_Updated()
        {
            // Setup test server and client
            using var server = await _host.StartAsync();

            var httpClient = server.GetTestClient();

            string userId = Guid.NewGuid().ToString();

            // Create a GRPC communication channel between the client and the server
            var channel = GrpcChannel.ForAddress(httpClient.BaseAddress, new GrpcChannelOptions
            {
                HttpClient = httpClient
            });

            var client  = new CartServiceClient(channel);
            var request = new AddItemRequest
            {
                UserId = userId,
                Item   = new CartItem
                {
                    ProductId = "1",
                    Quantity  = 1
                }
            };

            // First add - nothing should fail
            await client.AddItemAsync(request);

            // Second add of existing product - quantity should be updated
            await client.AddItemAsync(request);

            var getCartRequest = new GetCartRequest
            {
                UserId = userId
            };
            var cart = await client.GetCartAsync(getCartRequest);

            Assert.NotNull(cart);
            Assert.Equal(userId, cart.UserId);
            Assert.Single(cart.Items);
            Assert.Equal(2, cart.Items[0].Quantity);

            // Cleanup
            await client.EmptyCartAsync(new EmptyCartRequest { UserId = userId });
        }
Beispiel #5
0
        public async Task AddItem_New_Inserted()
        {
            // Setup test server and client
            using var server = await _host.StartAsync();

            var httpClient = server.GetTestClient();

            string userId = Guid.NewGuid().ToString();

            // Create a GRPC communication channel between the client and the server
            var channel = GrpcChannel.ForAddress(httpClient.BaseAddress, new GrpcChannelOptions
            {
                HttpClient = httpClient
            });

            // Create a proxy object to work with the server
            var client = new CartServiceClient(channel);

            var request = new AddItemRequest
            {
                UserId = userId,
                Item   = new CartItem
                {
                    ProductId = "1",
                    Quantity  = 1
                }
            };

            await client.AddItemAsync(request);

            var getCartRequest = new GetCartRequest
            {
                UserId = userId
            };
            var cart = await client.GetCartAsync(getCartRequest);

            Assert.NotNull(cart);
            Assert.Equal(userId, cart.UserId);
            Assert.Single(cart.Items);

            await client.EmptyCartAsync(new EmptyCartRequest { UserId = userId });

            cart = await client.GetCartAsync(getCartRequest);

            Assert.Empty(cart.Items);
        }
        public override async Task GetCart(GetCartRequest request, IServerStreamWriter <GetCartResponse> responseStream, ServerCallContext context)
        {
            var filter = new FilterDefinitionBuilder <BsonDocument>().Empty;
            var result = mongoCollection.Find(filter);

            foreach (var item in result.ToList())
            {
                await responseStream.WriteAsync(new GetCartResponse()
                {
                    Product = new Product.Product
                    {
                        Id    = item.GetValue("_id").ToString(),
                        Price = item.GetValue("price").AsDouble,
                        Title = item.GetValue("title").ToString()
                    }
                });

                Thread.Sleep(2000);
            }
        }
Beispiel #7
0
        public async Task AddItem_New_Inserted()
        {
            string userId = Guid.NewGuid().ToString();

            // Construct server's Uri
            string targetUri = $"{serverHostName}:{port}";

            // Create a GRPC communication channel between the client and the server
            var channel = new Channel(targetUri, ChannelCredentials.Insecure);

            // Create a proxy object to work with the server
            var client = new CartServiceClient(channel);

            var request = new AddItemRequest
            {
                UserId = userId,
                Item   = new CartItem
                {
                    ProductId = "1",
                    Quantity  = 1
                }
            };

            await client.AddItemAsync(request);

            var getCartRequest = new GetCartRequest
            {
                UserId = userId
            };
            var cart = await client.GetCartAsync(getCartRequest);

            Assert.NotNull(cart);
            Assert.Equal(userId, cart.UserId);
            Assert.Single(cart.Items);

            await client.EmptyCartAsync(new EmptyCartRequest { UserId = userId });

            cart = await client.GetCartAsync(getCartRequest);

            Assert.Empty(cart.Items);
        }
Beispiel #8
0
        public async Task AddItem_ItemExists_Updated()
        {
            string userId = Guid.NewGuid().ToString();

            // Construct server's Uri
            string targetUri = $"{serverHostName}:{port}";

            // Create a GRPC communication channel between the client and the server
            var channel = new Channel(targetUri, ChannelCredentials.Insecure);

            var client  = new CartServiceClient(channel);
            var request = new AddItemRequest
            {
                UserId = userId,
                Item   = new CartItem
                {
                    ProductId = "1",
                    Quantity  = 1
                }
            };

            // First add - nothing should fail
            await client.AddItemAsync(request);

            // Second add of existing product - quantity should be updated
            await client.AddItemAsync(request);

            var getCartRequest = new GetCartRequest
            {
                UserId = userId
            };
            var cart = await client.GetCartAsync(getCartRequest);

            Assert.NotNull(cart);
            Assert.Equal(userId, cart.UserId);
            Assert.Single(cart.Items);
            Assert.Equal(2, cart.Items[0].Quantity);

            // Cleanup
            await client.EmptyCartAsync(new EmptyCartRequest { UserId = userId });
        }
Beispiel #9
0
        public override async Task <GetCartResponse> GetCart(GetCartRequest request, ServerCallContext context)
        {
            try
            {
                var cartQuery = _queryFactory.QueryEfRepository <Domain.Cart>();

                var cart = await cartQuery.GetFullCartAsync(request.CartId.ConvertTo <Guid>(), false)
                           .ToObservable()
                           .SelectMany(async c =>
                                       await c.CalculateCartAsync(TaxType.NoTax, _catalogGateway, _promoGateway, _shippingGateway));

                return(new GetCartResponse {
                    Result = cart.ToDto()
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                throw new RpcException(new Status(StatusCode.Internal, ex.Message));
            }
        }
Beispiel #10
0
        public async Task GetItem_NoAddItemBefore_EmptyCartReturned()
        {
            string userId = Guid.NewGuid().ToString();

            // Create a GRPC communication channel between the client and the server
            using (var channel = GrpcChannel.ForAddress(TargetUrl))
            {
                var client = new CartServiceClient(channel);

                var request = new GetCartRequest
                {
                    UserId = userId,
                };
                var cart = await client.GetCartAsync(request);

                Assert.NotNull(cart);

                // All grpc objects implement IEquitable, so we can compare equality with by-value semantics
                Assert.Equal(new Cart(), cart);
            }
        }
        /// <summary>
        /// Retrieve a cart.
        /// The cart is created if it does not exist.
        /// </summary>
        /// <param name="param"></param>
        /// <returns>The Processed Cart requested or an empty one if it doesn't exist</returns>
        public virtual Task <ProcessedCart> GetCartAsync(GetCartParam param)
        {
            if (param == null)
            {
                throw new ArgumentNullException(nameof(param));
            }
            if (string.IsNullOrWhiteSpace(param.Scope))
            {
                throw new ArgumentException(GetMessageOfNullWhiteSpace(nameof(param.Scope)), nameof(param));
            }
            if (param.CultureInfo == null)
            {
                throw new ArgumentException(GetMessageOfNull(nameof(param.CultureInfo)), nameof(param));
            }
            if (string.IsNullOrWhiteSpace(param.CartName))
            {
                throw new ArgumentException(GetMessageOfNullWhiteSpace(nameof(param.CartName)), nameof(param));
            }
            if (param.CustomerId == Guid.Empty)
            {
                throw new ArgumentException(GetMessageOfEmpty(nameof(param.CustomerId)), nameof(param));
            }

            var cacheKey = BuildCartCacheKey(param.Scope, param.CustomerId, param.CartName);

            var request = new GetCartRequest
            {
                CultureName = param.CultureInfo.Name,
                CustomerId  = param.CustomerId,
                ScopeId     = param.Scope,
                CartName    = param.CartName,
                CartType    = param.CartType,
                //Reexecute price engine and promotion engine is automatically done at each request
                ExecuteWorkflow   = param.ExecuteWorkflow,
                WorkflowToExecute = param.WorkflowToExecute
            };

            return(CacheProvider.GetOrAddAsync(cacheKey, () => OvertureClient.SendAsync(request)));
        }
Beispiel #12
0
        public async Task AddItem_New_Inserted()
        {
            string userId = Guid.NewGuid().ToString();

            // Create a GRPC communication channel between the client and the server
            using (var channel = GrpcChannel.ForAddress(TargetUrl))
            {
                // Create a proxy object to work with the server
                var client = new CartServiceClient(channel);

                var request = new AddItemRequest
                {
                    UserId = userId,
                    Item   = new CartItem
                    {
                        ProductId = "1",
                        Quantity  = 1
                    }
                };

                await client.AddItemAsync(request);

                var getCartRequest = new GetCartRequest
                {
                    UserId = userId
                };
                var cart = await client.GetCartAsync(getCartRequest);

                Assert.NotNull(cart);
                Assert.Equal(userId, cart.UserId);
                Assert.Single(cart.Items);

                await client.EmptyCartAsync(new EmptyCartRequest { UserId = userId });

                cart = await client.GetCartAsync(getCartRequest);

                Assert.Empty(cart.Items);
            }
        }
Beispiel #13
0
        public virtual async Task <ProcessedCart> GetWishListAsync(GetCartParam param)
        {
            if (param == null)
            {
                throw new ArgumentNullException("param", "param is required");
            }
            if (string.IsNullOrWhiteSpace(param.Scope))
            {
                throw new ArgumentException("param.Scope is required", "param");
            }
            if (param.CultureInfo == null)
            {
                throw new ArgumentException("param.CultureInfo is required", "param");
            }
            if (string.IsNullOrWhiteSpace(param.CartName))
            {
                throw new ArgumentException("param.CartName is required", "param");
            }
            if (param.CustomerId == Guid.Empty)
            {
                throw new ArgumentException("param.CustomerId is required", "param");
            }

            var cacheKey = BuildWishListCacheKey(param.Scope, param.CustomerId, param.CartName);

            var request = new GetCartRequest
            {
                CultureName       = param.CultureInfo.Name,
                CustomerId        = param.CustomerId,
                ScopeId           = param.Scope,
                CartName          = param.CartName,
                ExecuteWorkflow   = param.ExecuteWorkflow,
                WorkflowToExecute = param.WorkflowToExecute
            };

            return(await CacheProvider.GetOrAddAsync(cacheKey, () => OvertureClient.SendAsync(request)).ConfigureAwait(false));
        }
Beispiel #14
0
        public async Task GetItem_NoAddItemBefore_EmptyCartReturned()
        {
            string userId = Guid.NewGuid().ToString();

            // Construct server's Uri
            string targetUri = $"{serverHostName}:{port}";

            // Create a GRPC communication channel between the client and the server
            var channel = new Channel(targetUri, ChannelCredentials.Insecure);

            var client = new CartServiceClient(channel);

            var request = new GetCartRequest
            {
                UserId = userId,
            };

            var cart = await client.GetCartAsync(request);

            Assert.NotNull(cart);

            // All grpc objects implement IEquitable, so we can compare equality with by-value semantics
            Assert.Equal(new Cart(), cart);
        }
Beispiel #15
0
 public override Task <Cart> GetCart(GetCartRequest request, ServerCallContext context)
 {
     _logger.LogInformation("CartService.GetCart UserId={UserId}", request.UserId);
     return(_cartStore.GetCartAsync(request.UserId));
 }
Beispiel #16
0
 public ActionResult <GetCartResponse> Get([FromRoute] GetCartRequest request)
 {
     return(Ok(Mediator.Send(request)));
 }
        public JsonResult GetCart(GetCartRequest request)
        {
            GetCartResponse response = bll.GetCart(request);

            return(Json(response));
        }
Beispiel #18
0
 public GetCartResponse GetCart(GetCartRequest request)
 {
     return(ApiRequestHelper.Post <GetCartRequest, GetCartResponse>(request));
 }
 public GetCartResponse GetCart(GetCartRequest request)
 {
     CheckConfiguration();
     return(GetCartAsync(request).Result);
 }
 public override Task <Hipstershop.Cart> GetCart(GetCartRequest request, ServerCallContext context)
 {
     using var parent = ActivitySource.StartActivity("hipstershop.CartService/GetCart", ActivityKind.Server);
     return(cartStore.GetCartAsync(request.UserId));
 }
Beispiel #21
0
        public async Task <IActionResult> GetCartAsync()
        {
            var request = new GetCartRequest(User.GetSubjectId());

            return(await _mediator.Send(request));
        }
 public override Task <Hipstershop.Cart> GetCart(GetCartRequest request, ServerCallContext context)
 {
     return(cartStore.GetCartAsync(request.UserId));
 }
Beispiel #23
0
 public Either <Error, GetCartResponse> Handle(GetCartRequest input)
 => _cartRepository.Get(input.CartId).TryGetValue(out var cart)
Beispiel #24
0
 public JsonResult GetCart(GetCartRequest request)
 {
     return(Json(bll.GetCart(request)));
 }