From 5e743f0e305d498ab9d5b35e7784749801b644d5 Mon Sep 17 00:00:00 2001 From: tniezg Date: Tue, 24 Aug 2021 16:25:05 +0200 Subject: [PATCH] Create a new cart if Spree can't find the current using a token --- framework/spree/cart/use-cart.tsx | 57 ++++++++++++------- .../utils/create-customized-fetch-fetcher.ts | 4 ++ 2 files changed, 39 insertions(+), 22 deletions(-) diff --git a/framework/spree/cart/use-cart.tsx b/framework/spree/cart/use-cart.tsx index a635ce0ff..e51e01ffd 100644 --- a/framework/spree/cart/use-cart.tsx +++ b/framework/spree/cart/use-cart.tsx @@ -8,6 +8,7 @@ import type { GraphQLFetcherResult } from '@commerce/api' import type { IOrder } from '@spree/storefront-api-v2-sdk/types/interfaces/Order' import type { IToken } from '@spree/storefront-api-v2-sdk/types/interfaces/Token' import setCartToken from '@framework/utils/set-cart-token' +import { FetcherError } from '@commerce/utils/errors' export default useCart as UseCart @@ -35,29 +36,41 @@ export const handler: SWRHook = { spreeCartResponse = null } else { const spreeToken: IToken = { orderToken: cartToken } - const { - data: { data: spreeCartShowSuccessResponse }, - } = await fetch>({ - variables: { - methodPath: 'cart.show', - arguments: [ - spreeToken, - { - include: [ - 'line_items', - 'line_items.variant', - 'line_items.variant.product', - 'line_items.variant.product.images', - 'line_items.variant.images', - 'line_items.variant.option_values', - 'line_items.variant.product.option_types', - ].join(','), - }, - ], - }, - }) - spreeCartResponse = spreeCartShowSuccessResponse + try { + const { + data: { data: spreeCartShowSuccessResponse }, + } = await fetch>({ + variables: { + methodPath: 'cart.show', + arguments: [ + spreeToken, + { + include: [ + 'line_items', + 'line_items.variant', + 'line_items.variant.product', + 'line_items.variant.product.images', + 'line_items.variant.images', + 'line_items.variant.option_values', + 'line_items.variant.product.option_types', + ].join(','), + }, + ], + }, + }) + + spreeCartResponse = spreeCartShowSuccessResponse + } catch (fetchCartError) { + if ( + !(fetchCartError instanceof FetcherError) || + fetchCartError.status !== 404 + ) { + throw fetchCartError + } + + spreeCartResponse = null + } } if (!spreeCartResponse || spreeCartResponse?.data.attributes.completed_at) { diff --git a/framework/spree/utils/create-customized-fetch-fetcher.ts b/framework/spree/utils/create-customized-fetch-fetcher.ts index 4adb64a45..eeeb10cae 100644 --- a/framework/spree/utils/create-customized-fetch-fetcher.ts +++ b/framework/spree/utils/create-customized-fetch-fetcher.ts @@ -60,6 +60,10 @@ const createCustomizedFetchFetcher: CreateCustomizedFetchFetcher = ( data: Object.setPrototypeOf({ data }, { response }), } } catch (error) { + if (error instanceof FetchError) { + throw error + } + throw new FetchError(null, request, null, error.message) } } catch (error) {