Create a new cart if Spree can't find the current using a token

This commit is contained in:
tniezg 2021-08-24 16:25:05 +02:00
parent d98a75503d
commit 5e743f0e30
2 changed files with 39 additions and 22 deletions

View File

@ -8,6 +8,7 @@ import type { GraphQLFetcherResult } from '@commerce/api'
import type { IOrder } from '@spree/storefront-api-v2-sdk/types/interfaces/Order' 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 type { IToken } from '@spree/storefront-api-v2-sdk/types/interfaces/Token'
import setCartToken from '@framework/utils/set-cart-token' import setCartToken from '@framework/utils/set-cart-token'
import { FetcherError } from '@commerce/utils/errors'
export default useCart as UseCart<typeof handler> export default useCart as UseCart<typeof handler>
@ -35,6 +36,8 @@ export const handler: SWRHook<GetCartHook> = {
spreeCartResponse = null spreeCartResponse = null
} else { } else {
const spreeToken: IToken = { orderToken: cartToken } const spreeToken: IToken = { orderToken: cartToken }
try {
const { const {
data: { data: spreeCartShowSuccessResponse }, data: { data: spreeCartShowSuccessResponse },
} = await fetch<GraphQLFetcherResult<{ data: IOrder }>>({ } = await fetch<GraphQLFetcherResult<{ data: IOrder }>>({
@ -58,6 +61,16 @@ export const handler: SWRHook<GetCartHook> = {
}) })
spreeCartResponse = spreeCartShowSuccessResponse spreeCartResponse = spreeCartShowSuccessResponse
} catch (fetchCartError) {
if (
!(fetchCartError instanceof FetcherError) ||
fetchCartError.status !== 404
) {
throw fetchCartError
}
spreeCartResponse = null
}
} }
if (!spreeCartResponse || spreeCartResponse?.data.attributes.completed_at) { if (!spreeCartResponse || spreeCartResponse?.data.attributes.completed_at) {

View File

@ -60,6 +60,10 @@ const createCustomizedFetchFetcher: CreateCustomizedFetchFetcher = (
data: Object.setPrototypeOf({ data }, { response }), data: Object.setPrototypeOf({ data }, { response }),
} }
} catch (error) { } catch (error) {
if (error instanceof FetchError) {
throw error
}
throw new FetchError(null, request, null, error.message) throw new FetchError(null, request, null, error.message)
} }
} catch (error) { } catch (error) {