Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
frandiox committed Jun 18, 2024
1 parent cb64392 commit acf5fc5
Showing 1 changed file with 9 additions and 24 deletions.
33 changes: 9 additions & 24 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,37 +54,22 @@ 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(),
}),
]);

const result = formatAPIResult(
addCustomerLoggedInParam(isCustomerLoggedIn, cart),
errors,
);
if (isCustomerLoggedIn && cart?.checkoutUrl) {
const finalCheckoutUrl = new URL(cart.checkoutUrl);
finalCheckoutUrl.searchParams.set('logged_in', 'true');
cart.checkoutUrl = finalCheckoutUrl.toString();
}

return Object.keys(result).length === 0 ? null : result;
return cart || errors ? formatAPIResult(cart, errors) : null;
};
}

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();
}

return cart;
}

//! @see https://shopify.dev/docs/api/storefront/latest/queries/cart
const CART_QUERY = (cartFragment = DEFAULT_CART_FRAGMENT) => `#graphql
query CartQuery(
Expand Down

0 comments on commit acf5fc5

Please sign in to comment.