Skip to content

Commit

Permalink
Merge pull request #227 from scottyzen/enhancement/fragment-refactoring
Browse files Browse the repository at this point in the history
Enhancement/fragment refactoring
  • Loading branch information
scottyzen authored Aug 19, 2024
2 parents b8bebd6 + c761440 commit fad0a76
Show file tree
Hide file tree
Showing 15 changed files with 78 additions and 100 deletions.
2 changes: 1 addition & 1 deletion woonuxt_base/app/composables/useAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const useAuth = () => {
const { loginWithCookies } = await GqlLogin(credentials);

if (loginWithCookies?.status === 'SUCCESS') {
const { viewer } = await refreshCart();
await refreshCart();
if (viewer === null) {
return {
success: false,
Expand Down
59 changes: 32 additions & 27 deletions woonuxt_base/app/composables/useCart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,34 +7,44 @@ import type { AddToCartInput } from '#gql';
export function useCart() {
const { storeSettings } = useAppConfig();

const cart = useState<Cart>('cart');
const cart = useState<Cart | null>('cart', () => null);
const isShowingCart = useState<boolean>('isShowingCart', () => false);
const isUpdatingCart = useState<boolean>('isUpdatingCart', () => false);
const isUpdatingCoupon = useState<boolean>('isUpdatingCoupon', () => false);
const paymentGateways = useState<PaymentGateways>('paymentGateways', () => null);
const paymentGateways = useState<PaymentGateways | null>('paymentGateways', () => null);
const { logGQLError, clearAllCookies } = useHelpers();

// Refesh the cart from the server
async function refreshCart() {
/** Refesh the cart from the server
* @returns {Promise<boolean>} - A promise that resolves
* to true if the cart was successfully refreshed
*/
async function refreshCart(): Promise<boolean> {
try {
const { cart, customer, viewer, paymentGateways } = await GqlGetCart();

const { updateCustomer, updateViewer } = useAuth();

if (cart) updateCart(cart);
if (customer) updateCustomer(customer);
if (viewer) updateViewer(viewer);
if (paymentGateways) updatePaymentGateways(paymentGateways);

return { cart, customer, viewer, paymentGateways };
return true; // Cart was successfully refreshed
} catch (error: any) {
logGQLError(error);
clearAllCookies();
return { cart: null, customer: null, viewer: null, paymentGateways: null };
resetInitialState();

return false;
}
}

function updateCart(payload: Cart | null): void {
cart.value = payload;
function resetInitialState() {
cart.value = null;
paymentGateways.value = null;
}

function updateCart(payload?: Cart | null): void {
cart.value = payload || null;
}

function updatePaymentGateways(payload: PaymentGateways): void {
Expand All @@ -52,7 +62,7 @@ export function useCart() {

try {
const { addToCart } = await GqlAddToCart({ input });
cart.value = addToCart?.cart ?? null;
if (addToCart?.cart) cart.value = addToCart.cart;
// Auto open the cart when an item is added to the cart if the setting is enabled
const { storeSettings } = useAppConfig();
if (storeSettings.autoOpenCart && !isShowingCart.value) toggleCart(true);
Expand All @@ -65,19 +75,17 @@ export function useCart() {
async function removeItem(key: string) {
isUpdatingCart.value = true;
const { updateItemQuantities } = await GqlUpDateCartQuantity({ key, quantity: 0 });
cart.value = updateItemQuantities?.cart ?? null;
updateCart(updateItemQuantities?.cart);
}

// update the quantity of an item in the cart
async function updateItemQuantity(key: string, quantity: number): Promise<number | undefined> {
async function updateItemQuantity(key: string, quantity: number): Promise<void> {
isUpdatingCart.value = true;
try {
const { updateItemQuantities } = await GqlUpDateCartQuantity({ key, quantity });
cart.value = updateItemQuantities?.cart ?? null;
return quantity;
updateCart(updateItemQuantities?.cart);
} catch (error: any) {
logGQLError(error);
return undefined;
}
}

Expand All @@ -86,7 +94,7 @@ export function useCart() {
try {
isUpdatingCart.value = true;
const { emptyCart } = await GqlEmptyCart();
updateCart(emptyCart?.cart ?? null);
updateCart(emptyCart?.cart);
} catch (error: any) {
logGQLError(error);
}
Expand All @@ -96,15 +104,15 @@ export function useCart() {
async function updateShippingMethod(shippingMethods: string) {
isUpdatingCart.value = true;
const { updateShippingMethod } = await GqlChangeShippingMethod({ shippingMethods });
cart.value = updateShippingMethod?.cart ?? null;
updateCart(updateShippingMethod?.cart);
}

// Apply coupon
async function applyCoupon(code: string): Promise<{ message: string | null }> {
try {
isUpdatingCoupon.value = true;
const { applyCoupon } = await GqlApplyCoupon({ code });
cart.value = applyCoupon?.cart ?? null;
updateCart(applyCoupon?.cart);
isUpdatingCoupon.value = false;
} catch (error: any) {
isUpdatingCoupon.value = false;
Expand All @@ -118,28 +126,25 @@ export function useCart() {
try {
isUpdatingCart.value = true;
const { removeCoupons } = await GqlRemoveCoupons({ codes: [code] });
cart.value = removeCoupons?.cart ?? null;
isUpdatingCart.value = false;
updateCart(removeCoupons?.cart);
} catch (error) {
logGQLError(error);
isUpdatingCart.value = false;
}
}

// Stop the loading spinner when the cart is updated
watch(cart, (val) => {
isUpdatingCart.value = false;
});

// Check if all products in the cart are virtual
const allProductsAreVirtual = computed(() => {
const nodes = cart.value?.contents?.nodes || [];
if (nodes.length === 0) return false;

return nodes.every((node) => {
const product = node.product?.node as SimpleProduct;
return product?.virtual === true;
});
return nodes.length === 0 ? false : nodes.every((node) => (node.product?.node as SimpleProduct)?.virtual === true);
});

// Check if the billing address is enabled
const isBillingAddressEnabled = computed(() => (storeSettings.hideBillingAddressForVirtualProducts ? !allProductsAreVirtual.value : true));

return {
Expand All @@ -148,6 +153,7 @@ export function useCart() {
isUpdatingCart,
isUpdatingCoupon,
paymentGateways,
isBillingAddressEnabled,
updateCart,
refreshCart,
toggleCart,
Expand All @@ -158,6 +164,5 @@ export function useCart() {
updateShippingMethod,
applyCoupon,
removeCoupon,
isBillingAddressEnabled,
};
}
6 changes: 3 additions & 3 deletions woonuxt_base/app/plugins/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export default defineNuxtPlugin(async (nuxtApp) => {
initialised = true;

const { refreshCart } = useCart();
const success = await refreshCart();
const success: boolean = await refreshCart();

useGqlError((err: any) => {
const serverErrors = ['The iss do not match with this server', 'Invalid session token'];
Expand Down Expand Up @@ -54,10 +54,10 @@ export default defineNuxtPlugin(async (nuxtApp) => {

// If we are in development mode, we want to initialise the store immediately
const isDev = process.env.NODE_ENV === 'development';

// Check if the current route path is one of the pages that need immediate initialization
const pagesToInitializeRightAway = ['/checkout', '/my-account', '/order-summary'];
const isPathThatRequiresInit = pagesToInitializeRightAway.some(page => useRoute().path.includes(page));
const isPathThatRequiresInit = pagesToInitializeRightAway.some((page) => useRoute().path.includes(page));

const shouldInit = isDev || isPathThatRequiresInit || !storeSettings.initStoreOnUserActionToReduceServerLoad;

Expand Down
2 changes: 1 addition & 1 deletion woonuxt_base/app/queries/addToCart.gql
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
mutation addToCart($input: AddToCartInput!) {
addToCart(input: $input) {
cart {
...CartFragment
...Cart
}
}
}
2 changes: 1 addition & 1 deletion woonuxt_base/app/queries/applyCoupon.gql
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ mutation applyCoupon($code: String!) {
discountAmount
}
cart {
...CartFragment
...Cart
}
}
}
2 changes: 1 addition & 1 deletion woonuxt_base/app/queries/changeShippingMethod.gql
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
mutation ChangeShippingMethod($shippingMethods: [String] = "") {
updateShippingMethod(input: { shippingMethods: $shippingMethods }) {
cart {
...CartFragment
...Cart
}
}
}
2 changes: 1 addition & 1 deletion woonuxt_base/app/queries/emptyCart.gql
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
mutation EmptyCart {
emptyCart(input: { clearPersistentCart: true }) {
cart {
...CartFragment
...Cart
}
}
}
2 changes: 1 addition & 1 deletion woonuxt_base/app/queries/fragments/CartFragment.gql
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
fragment CartFragment on Cart {
fragment Cart on Cart {
total
rawTotal: total(format: RAW)
subtotal
Expand Down
2 changes: 1 addition & 1 deletion woonuxt_base/app/queries/fragments/CustomerFragment.gql
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
fragment CustomerFragment on Customer {
fragment Customer on Customer {
lastName
email
firstName
Expand Down
2 changes: 1 addition & 1 deletion woonuxt_base/app/queries/fragments/OrderFragment.gql
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,6 @@ fragment OrderFragment on Order {
}
}
customer {
...CustomerFragment
...Customer
}
}
44 changes: 26 additions & 18 deletions woonuxt_base/app/queries/getCart.gql
Original file line number Diff line number Diff line change
@@ -1,28 +1,36 @@
query getCart {
cart {
...CartFragment
...Cart
}
customer {
...CustomerFragment
...Customer
}
viewer {
lastName
email
databaseId
id
firstName
username
nicename
wooSessionToken
avatar {
url
}
...Viewer
}
paymentGateways {
nodes {
title
id
description
}
...PaymentGateways
}
}

fragment Viewer on User {
lastName
email
databaseId
id
firstName
username
nicename
wooSessionToken
avatar {
url
}
}

fragment PaymentGateways on RootQueryToPaymentGatewayConnection {
nodes {
title
id
description
}
}
2 changes: 1 addition & 1 deletion woonuxt_base/app/queries/registerCustomer.gql
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
mutation registerCustomer($input: RegisterCustomerInput!) {
registerCustomer(input: $input) {
customer {
...CustomerFragment
...Customer
}
}
}
2 changes: 1 addition & 1 deletion woonuxt_base/app/queries/removeCoupon.gql
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
mutation removeCoupons($codes: [String]!) {
removeCoupons(input: { codes: $codes }) {
cart {
...CartFragment
...Cart
}
}
}
2 changes: 1 addition & 1 deletion woonuxt_base/app/queries/updateCartQuantity.gql
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
mutation UpDateCartQuantity($key: ID!, $quantity: Int!) {
updateItemQuantities(input: { items: { key: $key, quantity: $quantity } }) {
cart {
...CartFragment
...Cart
}
}
}
Loading

0 comments on commit fad0a76

Please sign in to comment.