Skip to content

Commit

Permalink
Fix cart.get() returning empty object for invalid ids (#2258)
Browse files Browse the repository at this point in the history
* Return cart null instead of empty object

* Changesets

* Refactor
  • Loading branch information
frandiox authored Jun 19, 2024
1 parent 67a634f commit de3f70b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 23 deletions.
5 changes: 5 additions & 0 deletions .changeset/wise-badgers-march.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@shopify/hydrogen': patch
---

Return `null` instead of empty object from `cart.get()` when the cart id is invalid.
33 changes: 10 additions & 23 deletions packages/hydrogen/src/cart/queries/cartGetDefault.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {StorefrontApiErrors, formatAPIResult} from '../../storefront';
import {formatAPIResult} from '../../storefront';
import type {CustomerAccount} from '../../customer/types';
import type {CartQueryOptions, CartReturn} from './cart-types';
import type {
Expand Down Expand Up @@ -54,33 +54,20 @@ export function cartGetDefault({

const [isCustomerLoggedIn, {cart, errors}] = await Promise.all([
customerAccount ? customerAccount.isLoggedIn() : false,
storefront.query<{
cart: Cart;
errors: StorefrontApiErrors;
}>(CART_QUERY(cartFragment), {
variables: {
cartId,
...cartInput,
},
storefront.query<{cart: Cart | null}>(CART_QUERY(cartFragment), {
variables: {cartId, ...cartInput},
cache: storefront.CacheNone(),
}),
]);

return formatAPIResult(
addCustomerLoggedInParam(isCustomerLoggedIn, cart),
errors,
);
};
}

function addCustomerLoggedInParam(isCustomerLoggedIn: boolean, cart: Cart) {
if (isCustomerLoggedIn && cart && cart.checkoutUrl) {
const finalCheckoutUrl = new URL(cart.checkoutUrl);
finalCheckoutUrl.searchParams.set('logged_in', 'true');
cart.checkoutUrl = finalCheckoutUrl.toString();
}
if (isCustomerLoggedIn && cart?.checkoutUrl) {
const finalCheckoutUrl = new URL(cart.checkoutUrl);
finalCheckoutUrl.searchParams.set('logged_in', 'true');
cart.checkoutUrl = finalCheckoutUrl.toString();
}

return cart;
return cart || errors ? formatAPIResult(cart, errors) : null;
};
}

//! @see https://shopify.dev/docs/api/storefront/latest/queries/cart
Expand Down

0 comments on commit de3f70b

Please sign in to comment.