From 2e52e0f979abeb466f7a5ad73f397ce584f3759a Mon Sep 17 00:00:00 2001 From: Martin Kyjac Date: Fri, 17 May 2024 16:43:35 +0200 Subject: [PATCH] Add error message if cart operation does not exist --- .../Shopify/ShopifyShoppingCartController.cs | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/examples/DancingGoat-Shopify/Controllers/Shopify/ShopifyShoppingCartController.cs b/examples/DancingGoat-Shopify/Controllers/Shopify/ShopifyShoppingCartController.cs index 5ca9152..2a7b281 100644 --- a/examples/DancingGoat-Shopify/Controllers/Shopify/ShopifyShoppingCartController.cs +++ b/examples/DancingGoat-Shopify/Controllers/Shopify/ShopifyShoppingCartController.cs @@ -22,6 +22,8 @@ namespace DancingGoat.Controllers.Shopify { public class ShopifyShoppingCartController : Controller { + private const string ERROR_MESSAGES_KEY = "ErrorMessages"; + private readonly IShoppingService shoppingService; private readonly IShopifyContentItemService contentItemService; private readonly IWebPageUrlRetriever webPageUrlRetriever; @@ -47,7 +49,7 @@ public async Task Index() { var cart = await shoppingService.GetCurrentShoppingCart(); ShoppingCartContentViewModel model = null; - string[] errorMessages = TempData["ErrorMessages"] as string[] ?? []; + string[] errorMessages = TempData[ERROR_MESSAGES_KEY] as string[] ?? []; string language = currentLanguageRetriever.Get(); string storePageUrl = (await webPageUrlRetriever.Retrieve(DancingGoatConstants.STORE_PAGE_PATH, websiteChannelContext.WebsiteChannelName, language)).RelativePath; if (cart == null) @@ -77,9 +79,9 @@ public async Task Index() public async Task Update([FromForm] string variantGraphQLId, [FromForm] int quantity, [FromForm] string cartOperation) { var country = ShopifySharp.GraphQL.CountryCode.CZ; - var operationEnum = Enum.Parse(cartOperation); - - var result = operationEnum == CartOperation.Remove + if (Enum.TryParse(cartOperation, out var operationEnum)) + { + var result = operationEnum == CartOperation.Remove ? await shoppingService.RemoveCartItem(variantGraphQLId) : await shoppingService.UpdateCartItem(new ShoppingCartItemParameters() { @@ -88,7 +90,13 @@ public async Task Update([FromForm] string variantGraphQLId, [Fro MerchandiseID = variantGraphQLId }); - AddErrorsToTempData(result); + AddErrorsToTempData(result); + } + else + { + TempData[ERROR_MESSAGES_KEY] = new string[] { $"Invalid operation name {cartOperation}." }; + } + return Redirect(await GetCartUrl()); } @@ -134,7 +142,7 @@ private void AddErrorsToTempData(CartOperationResult result) { if (!result.Success) { - TempData["ErrorMessages"] = result.ErrorMessages.ToArray(); + TempData[ERROR_MESSAGES_KEY] = result.ErrorMessages.ToArray(); } }