mirror of
https://github.com/vercel/commerce.git
synced 2025-03-31 17:25:53 +00:00
Variants Issue with Shopify Provider (#222)
* changes * Progress * Normalized Products output * Progress * Restored Index Agnostic * Progress * Reordering * Moved normalizer to BC function * Removed Futures * More Types * More Types * More Types * Fix useCallback * Progress, Changes types, readme and restoring functionality * Changes * TS Issues * Changes * Normalizer * Normalizing more operations * Normalizing more operations * changes * Merge Issues * Cleanup * change * changes * index.ts broke my tree shaking * slug * Normalized Options and Swatches * Restored Add to cart * Correct Variant Added to Cart * Normalizing Cart Responses * Changes * changes breaking * Adding immutable normalizer for Product * Cart Normalized * changes * Progress * More updates * Removed some comments * Add loading state for data hooks * Bug fix * Changed the way isEmpty works * Improve navbar performance * Added useResponse hook * added useResponse to useWhishlist * Added husky and lint-staged * Ran prettier fix * Added more cart types * Moved types.d.ts to the commerce folder * Minor changes * Moved normalizer to happen after fetch * updated useCart types * Updated normalizer for useData * Added new normalizer for the cart to the UI * More corrections for useCart * Updated cart update hooks * Removed import * Progress * Switch away from global types * Making multiple changes * Improved types for operations * Moved and updated cart types * Updated the useAddItem and useRemoveItem hooks * Minor life improvement * Minor change * Implement Shopify Provider * Update README.md * Update README.md * normalizations & missing files * Update index.ts * fixes * Update normalize.ts * fix: cart error on first load * shopify checkout redirect & api handler * Update get-checkout-id.ts * userAvatar * Fix: color option * Update normalize.ts * changes * Update next.config.js * start customer auth & signup * Update config.ts * Login, Sign Up, Log Out, and checkout & customer association * Automatic login after sign-up * Update handle-login.ts * MOving stuff around and adding temporal new files * changes * Replace use-cart with the new hook * Removed old hook * Improved HookHandler type * Moved types * Simplified useData types * Updated Fetcher type * Moved SwrOptions type * Removed duplicated fetcher * Moved provider to its own file * Added proper type for fetch input * Revert "Merge branch 'agnostic' of https://github.com/vercel/commerce into agnostic" This reverts commit 23c8ed7c2d48d30e74ad94216f9910650fadf30c, reversing changes made to bf50965a39ef0b1b956461ebe62070809fbe1d63. * change readme * Revert "Merge branch 'master' of https://github.com/vercel/commerce into agnostic" This reverts commit bf50965a39ef0b1b956461ebe62070809fbe1d63, reversing changes made to 0dad4ddedbf0bff2d0b5800ca469fda0073889ea. * Revert "Revert "Merge branch 'agnostic' of https://github.com/vercel/commerce into agnostic"" This reverts commit c9a43f1bce0572d0eff41f3af893be8bdb00bedd. * align with upstream changes * Updated how the hook input is handled * Add more options to the hook handler * Final touches to the hook handler type * Moved useWishlist to use new handler * Move useCustomer to the new hook * Added a default fetcher * query all products for vendors & paths, improve search * Update use-search.tsx * fix cart after upstream changes * Shopify Provider (#186) * Start of Shopify provider * add missing comment to documentation * add missing env vars to documentation * update reference to types file * Moved useSearch to the new hook * Removed old use-data lib * Removed generics for result and body * Removed normalizr * Wishlist * New changes and initial Features API * Fixed some types * Fixed more types * fixes after upstream changes * Fixed product types * Fixed another product type * Updated type * Fixed remaining issues with types * Added a MutationHandler * Moved the handlers to each hook * Moved the fetcher to its own file * Moved handler to each hook * Added initial version of useAddItem * Added better mutation types, and moved some hooks * Removed use-cart-actions * Added initial version of useAddItem * Updated types * Update use-add-item.tsx * changes * Changes * Reordering and changes * Adding Features APO * Adding wishlist api * Implementing FeaturesAPI with Wishlist * Removing bug with touchstart * Adding tyni typing * moved use-remove-item * Removed MutationHandler type * Moved more hooks and updated types to make them smaller * Moved data hooks to new format * Removed no longer required types * Removed useResponse helper * Updated useData type * Moved wishlist use-add-item * Moved wishlist use-remove-item to provider * Moved use-login and use-logout * Update use-signup * Removed use-action helper * Moved auth & cart hooks + several fixes * Updated cart item, fixed deprecations * Update next.config.js * Updates to wishlist feature * Moved the features to be environment variable only * More changes for wishlist config * Disable wishlist * Removed useWishlistActions * Updated readme * updates * typos * Updated the way the provider config is set * Removed features.ts * Removed bootstrap.js * Aligned with upstream changes * Updates * shopify: changes * shopify: changes * Update next.config.js * Shopify Provider Updates (#209) * Implement Shopify Provider * Update README.md * Update README.md * normalizations & missing files * Update index.ts * fixes * Update normalize.ts * fix: cart error on first load * shopify checkout redirect & api handler * Update get-checkout-id.ts * Fix: color option * Update normalize.ts * changes * Update next.config.js * start customer auth & signup * Update config.ts * Login, Sign Up, Log Out, and checkout & customer association * Automatic login after sign-up * Update handle-login.ts * changes * Revert "Merge branch 'agnostic' of https://github.com/vercel/commerce into agnostic" This reverts commit 23c8ed7c2d48d30e74ad94216f9910650fadf30c, reversing changes made to bf50965a39ef0b1b956461ebe62070809fbe1d63. * change readme * Revert "Merge branch 'master' of https://github.com/vercel/commerce into agnostic" This reverts commit bf50965a39ef0b1b956461ebe62070809fbe1d63, reversing changes made to 0dad4ddedbf0bff2d0b5800ca469fda0073889ea. * Revert "Revert "Merge branch 'agnostic' of https://github.com/vercel/commerce into agnostic"" This reverts commit c9a43f1bce0572d0eff41f3af893be8bdb00bedd. * align with upstream changes * query all products for vendors & paths, improve search * Update use-search.tsx * fix cart after upstream changes * fixes after upstream changes * Moved handler to each hook * Added initial version of useAddItem * Updated types * Update use-add-item.tsx * Moved auth & cart hooks + several fixes * Updated cart item, fixed deprecations * Update next.config.js * Aligned with upstream changes * Updates * Update next.config.js * Updated the commerce config structure * Removed @framework imports within framework providers * Fixed types * changes * Adding extra config * Adding shopify commit * Adding env templates to the providers * Ignore some types * Adding link for Cart * Adding customCheckout * multiple changes to fix the wishlist * Shopify Provier Updates (#212) * changes * Adding shopify commit * Changed to query page by id * Fixed page query, Changed use-search GraphQl query * Update use-search.tsx * remove unused util * Changed cookie expiration * Update tsconfig.json Co-authored-by: okbel <curciobel@gmail.com> * Bump and adding dependency * Adding color checks * Now colors work with lighter colors * Stable commerce.config.json * Updated main readme * Readme changes * Default to bigcommerce * og config * Adding Shopify Config * Adding OG Card * Adding support for default option * Adding support for default options and removing the one that we do not need * Changes to Shopify * Shopify provider fixes (#225) * Changed to query page by id * Fixed page query, Changed use-search GraphQl query * Update use-search.tsx * remove unused util * Changed cookie expiration * Update tsconfig.json * Fix add to cart & prepare for user activation * Update helpers.ts * Update helpers.ts * Changes, fix Shopify GraphQL deprecations * Update checkout-to-cart.ts * Default to BigCommerce * Update index.ts * Fixed types * Delete commerce.config.json * Shopify provider fixes (#239) * Changed to query page by id * Fixed page query, Changed use-search GraphQl query * Update use-search.tsx * remove unused util * Changed cookie expiration * Update tsconfig.json * Fix add to cart & prepare for user activation * Update helpers.ts * Update helpers.ts * Changes, fix Shopify GraphQL deprecations * Update checkout-to-cart.ts * Default to BigCommerce * Update index.ts * Fixed types * Update customer-access-token-delete.ts * Fix item missing path * Update customer-access-token-delete.ts Co-authored-by: bc <bc@bcs-MacBook-Pro.fibertel.com.ar> Co-authored-by: Luis Alvarez <luis@vercel.com> Co-authored-by: cond0r <pinte_catalin@yahoo.com> Co-authored-by: Peter Mekhaeil <4616064+petermekhaeil@users.noreply.github.com>
This commit is contained in:
parent
936f149fcc
commit
d838f34c73
@ -1,23 +1,20 @@
|
|||||||
import cn from 'classnames'
|
import cn from 'classnames'
|
||||||
import Image from 'next/image'
|
import Image from 'next/image'
|
||||||
import { NextSeo } from 'next-seo'
|
import { NextSeo } from 'next-seo'
|
||||||
import { FC, useState } from 'react'
|
import { FC, useEffect, useState } from 'react'
|
||||||
import s from './ProductView.module.css'
|
import s from './ProductView.module.css'
|
||||||
|
|
||||||
import { Swatch, ProductSlider } from '@components/product'
|
import { Swatch, ProductSlider } from '@components/product'
|
||||||
import { Button, Container, Text, useUI } from '@components/ui'
|
import { Button, Container, Text, useUI } from '@components/ui'
|
||||||
|
|
||||||
import type { Product } from '@commerce/types'
|
import type { Product } from '@commerce/types'
|
||||||
import usePrice from '@framework/product/use-price'
|
import usePrice from '@framework/product/use-price'
|
||||||
import { useAddItem } from '@framework/cart'
|
import { useAddItem } from '@framework/cart'
|
||||||
|
|
||||||
import { getVariant, SelectedOptions } from '../helpers'
|
import { getVariant, SelectedOptions } from '../helpers'
|
||||||
import WishlistButton from '@components/wishlist/WishlistButton'
|
import WishlistButton from '@components/wishlist/WishlistButton'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
className?: string
|
|
||||||
children?: any
|
children?: any
|
||||||
product: Product
|
product: Product
|
||||||
|
className?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
const ProductView: FC<Props> = ({ product }) => {
|
const ProductView: FC<Props> = ({ product }) => {
|
||||||
@ -29,12 +26,18 @@ const ProductView: FC<Props> = ({ product }) => {
|
|||||||
})
|
})
|
||||||
const { openSidebar } = useUI()
|
const { openSidebar } = useUI()
|
||||||
const [loading, setLoading] = useState(false)
|
const [loading, setLoading] = useState(false)
|
||||||
const [choices, setChoices] = useState<SelectedOptions>({
|
const [choices, setChoices] = useState<SelectedOptions>({})
|
||||||
size: null,
|
|
||||||
color: null,
|
useEffect(() => {
|
||||||
})
|
// Selects the default option
|
||||||
|
product.variants[0].options?.forEach((v) => {
|
||||||
|
setChoices((choices) => ({
|
||||||
|
...choices,
|
||||||
|
[v.displayName.toLowerCase()]: v.values[0].label.toLowerCase(),
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
}, [])
|
||||||
|
|
||||||
// Select the correct variant based on choices
|
|
||||||
const variant = getVariant(product, choices)
|
const variant = getVariant(product, choices)
|
||||||
|
|
||||||
const addToCart = async () => {
|
const addToCart = async () => {
|
||||||
@ -143,7 +146,6 @@ const ProductView: FC<Props> = ({ product }) => {
|
|||||||
className={s.button}
|
className={s.button}
|
||||||
onClick={addToCart}
|
onClick={addToCart}
|
||||||
loading={loading}
|
loading={loading}
|
||||||
disabled={!variant && product.options.length > 0}
|
|
||||||
>
|
>
|
||||||
Add to Cart
|
Add to Cart
|
||||||
</Button>
|
</Button>
|
||||||
|
@ -1,9 +1,5 @@
|
|||||||
import type { Product } from '@commerce/types'
|
import type { Product } from '@commerce/types'
|
||||||
|
export type SelectedOptions = Record<string, string | null>
|
||||||
export type SelectedOptions = {
|
|
||||||
size: string | null
|
|
||||||
color: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getVariant(product: Product, opts: SelectedOptions) {
|
export function getVariant(product: Product, opts: SelectedOptions) {
|
||||||
const variant = product.variants.find((variant) => {
|
const variant = product.variants.find((variant) => {
|
||||||
|
@ -5,7 +5,6 @@ import {
|
|||||||
API_TOKEN,
|
API_TOKEN,
|
||||||
SHOPIFY_CHECKOUT_ID_COOKIE,
|
SHOPIFY_CHECKOUT_ID_COOKIE,
|
||||||
SHOPIFY_CUSTOMER_TOKEN_COOKIE,
|
SHOPIFY_CUSTOMER_TOKEN_COOKIE,
|
||||||
SHOPIFY_COOKIE_EXPIRE,
|
|
||||||
} from '../const'
|
} from '../const'
|
||||||
|
|
||||||
if (!API_URL) {
|
if (!API_URL) {
|
||||||
@ -48,7 +47,7 @@ const config = new Config({
|
|||||||
commerceUrl: API_URL,
|
commerceUrl: API_URL,
|
||||||
apiToken: API_TOKEN!,
|
apiToken: API_TOKEN!,
|
||||||
cartCookie: SHOPIFY_CHECKOUT_ID_COOKIE,
|
cartCookie: SHOPIFY_CHECKOUT_ID_COOKIE,
|
||||||
cartCookieMaxAge: SHOPIFY_COOKIE_EXPIRE,
|
cartCookieMaxAge: 60 * 60 * 24 * 30,
|
||||||
fetch: fetchGraphqlApi,
|
fetch: fetchGraphqlApi,
|
||||||
customerCookie: SHOPIFY_CUSTOMER_TOKEN_COOKIE,
|
customerCookie: SHOPIFY_CUSTOMER_TOKEN_COOKIE,
|
||||||
})
|
})
|
||||||
|
@ -1,21 +0,0 @@
|
|||||||
import Client from 'shopify-buy'
|
|
||||||
import { ShopifyConfig } from '../index'
|
|
||||||
|
|
||||||
type Options = {
|
|
||||||
config: ShopifyConfig
|
|
||||||
}
|
|
||||||
|
|
||||||
const getAllCollections = async (options: Options) => {
|
|
||||||
const { config } = options
|
|
||||||
|
|
||||||
const client = Client.buildClient({
|
|
||||||
storefrontAccessToken: config.apiToken,
|
|
||||||
domain: config.commerceUrl,
|
|
||||||
})
|
|
||||||
|
|
||||||
const res = await client.collection.fetchAllWithProducts()
|
|
||||||
|
|
||||||
return JSON.parse(JSON.stringify(res))
|
|
||||||
}
|
|
||||||
|
|
||||||
export default getAllCollections
|
|
@ -1,25 +0,0 @@
|
|||||||
import { Page } from '../../schema'
|
|
||||||
import { ShopifyConfig, getConfig } from '..'
|
|
||||||
|
|
||||||
export type GetPageResult<T extends { page?: any } = { page?: Page }> = T
|
|
||||||
|
|
||||||
export type PageVariables = {
|
|
||||||
id: string
|
|
||||||
}
|
|
||||||
|
|
||||||
async function getPage({
|
|
||||||
url,
|
|
||||||
variables,
|
|
||||||
config,
|
|
||||||
preview,
|
|
||||||
}: {
|
|
||||||
url?: string
|
|
||||||
variables: PageVariables
|
|
||||||
config?: ShopifyConfig
|
|
||||||
preview?: boolean
|
|
||||||
}): Promise<GetPageResult> {
|
|
||||||
config = getConfig(config)
|
|
||||||
return {}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default getPage
|
|
@ -10,7 +10,7 @@ import {
|
|||||||
MutationCheckoutCreateArgs,
|
MutationCheckoutCreateArgs,
|
||||||
} from '../schema'
|
} from '../schema'
|
||||||
import useLogin, { UseLogin } from '@commerce/auth/use-login'
|
import useLogin, { UseLogin } from '@commerce/auth/use-login'
|
||||||
import { setCustomerToken } from '../utils'
|
import { setCustomerToken, throwUserErrors } from '../utils'
|
||||||
|
|
||||||
export default useLogin as UseLogin<typeof handler>
|
export default useLogin as UseLogin<typeof handler>
|
||||||
|
|
||||||
@ -45,13 +45,8 @@ export const handler: MutationHook<null, {}, CustomerAccessTokenCreateInput> = {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const errors = customerAccessTokenCreate?.customerUserErrors
|
throwUserErrors(customerAccessTokenCreate?.customerUserErrors)
|
||||||
|
|
||||||
if (errors && errors.length) {
|
|
||||||
throw new ValidationError({
|
|
||||||
message: getErrorMessage(errors[0]),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
const customerAccessToken = customerAccessTokenCreate?.customerAccessToken
|
const customerAccessToken = customerAccessTokenCreate?.customerAccessToken
|
||||||
const accessToken = customerAccessToken?.accessToken
|
const accessToken = customerAccessToken?.accessToken
|
||||||
|
|
||||||
|
@ -1,15 +1,16 @@
|
|||||||
import { useCallback } from 'react'
|
import { useCallback } from 'react'
|
||||||
import type { MutationHook } from '@commerce/utils/types'
|
import type { MutationHook } from '@commerce/utils/types'
|
||||||
import { CommerceError } from '@commerce/utils/errors'
|
import { CommerceError, ValidationError } from '@commerce/utils/errors'
|
||||||
import useSignup, { UseSignup } from '@commerce/auth/use-signup'
|
import useSignup, { UseSignup } from '@commerce/auth/use-signup'
|
||||||
import useCustomer from '../customer/use-customer'
|
import useCustomer from '../customer/use-customer'
|
||||||
import { CustomerCreateInput } from '../schema'
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
customerCreateMutation,
|
CustomerCreateInput,
|
||||||
customerAccessTokenCreateMutation,
|
Mutation,
|
||||||
} from '../utils/mutations'
|
MutationCustomerCreateArgs,
|
||||||
import handleLogin from '../utils/handle-login'
|
} from '../schema'
|
||||||
|
|
||||||
|
import { customerCreateMutation } from '../utils/mutations'
|
||||||
|
import { handleAutomaticLogin, throwUserErrors } from '../utils'
|
||||||
|
|
||||||
export default useSignup as UseSignup<typeof handler>
|
export default useSignup as UseSignup<typeof handler>
|
||||||
|
|
||||||
@ -33,7 +34,11 @@ export const handler: MutationHook<
|
|||||||
'A first name, last name, email and password are required to signup',
|
'A first name, last name, email and password are required to signup',
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
const data = await fetch({
|
|
||||||
|
const { customerCreate } = await fetch<
|
||||||
|
Mutation,
|
||||||
|
MutationCustomerCreateArgs
|
||||||
|
>({
|
||||||
...options,
|
...options,
|
||||||
variables: {
|
variables: {
|
||||||
input: {
|
input: {
|
||||||
@ -45,19 +50,10 @@ export const handler: MutationHook<
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
try {
|
throwUserErrors(customerCreate?.customerUserErrors)
|
||||||
const loginData = await fetch({
|
await handleAutomaticLogin(fetch, { email, password })
|
||||||
query: customerAccessTokenCreateMutation,
|
|
||||||
variables: {
|
return null
|
||||||
input: {
|
|
||||||
email,
|
|
||||||
password,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
handleLogin(loginData)
|
|
||||||
} catch (error) {}
|
|
||||||
return data
|
|
||||||
},
|
},
|
||||||
useHook: ({ fetch }) => () => {
|
useHook: ({ fetch }) => () => {
|
||||||
const { revalidate } = useCustomer()
|
const { revalidate } = useCustomer()
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
export { default as useCart } from './use-cart'
|
export { default as useCart } from './use-cart'
|
||||||
export { default as useAddItem } from './use-add-item'
|
export { default as useAddItem } from './use-add-item'
|
||||||
|
export { default as useUpdateItem } from './use-update-item'
|
||||||
export { default as useRemoveItem } from './use-remove-item'
|
export { default as useRemoveItem } from './use-remove-item'
|
||||||
|
@ -1,12 +1,15 @@
|
|||||||
|
import { useCallback } from 'react'
|
||||||
import type { MutationHook } from '@commerce/utils/types'
|
import type { MutationHook } from '@commerce/utils/types'
|
||||||
import { CommerceError } from '@commerce/utils/errors'
|
import { CommerceError } from '@commerce/utils/errors'
|
||||||
import useAddItem, { UseAddItem } from '@commerce/cart/use-add-item'
|
import useAddItem, { UseAddItem } from '@commerce/cart/use-add-item'
|
||||||
import useCart from './use-cart'
|
import useCart from './use-cart'
|
||||||
|
import {
|
||||||
|
checkoutLineItemAddMutation,
|
||||||
|
getCheckoutId,
|
||||||
|
checkoutToCart,
|
||||||
|
} from '../utils'
|
||||||
import { Cart, CartItemBody } from '../types'
|
import { Cart, CartItemBody } from '../types'
|
||||||
import { checkoutLineItemAddMutation, getCheckoutId } from '../utils'
|
|
||||||
import { checkoutToCart } from './utils'
|
|
||||||
import { Mutation, MutationCheckoutLineItemsAddArgs } from '../schema'
|
import { Mutation, MutationCheckoutLineItemsAddArgs } from '../schema'
|
||||||
import { useCallback } from 'react'
|
|
||||||
|
|
||||||
export default useAddItem as UseAddItem<typeof handler>
|
export default useAddItem as UseAddItem<typeof handler>
|
||||||
|
|
||||||
@ -40,8 +43,7 @@ export const handler: MutationHook<Cart, {}, CartItemBody> = {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
// TODO: Fix this Cart type here
|
return checkoutToCart(checkoutLineItemsAdd)
|
||||||
return checkoutToCart(checkoutLineItemsAdd) as any
|
|
||||||
},
|
},
|
||||||
useHook: ({ fetch }) => () => {
|
useHook: ({ fetch }) => () => {
|
||||||
const { mutate } = useCart()
|
const { mutate } = useCart()
|
||||||
|
@ -6,7 +6,7 @@ import useCommerceCart, {
|
|||||||
|
|
||||||
import { Cart } from '../types'
|
import { Cart } from '../types'
|
||||||
import { SWRHook } from '@commerce/utils/types'
|
import { SWRHook } from '@commerce/utils/types'
|
||||||
import { checkoutCreate, checkoutToCart } from './utils'
|
import { checkoutCreate, checkoutToCart } from '../utils'
|
||||||
import getCheckoutQuery from '../utils/queries/get-checkout-query'
|
import getCheckoutQuery from '../utils/queries/get-checkout-query'
|
||||||
|
|
||||||
export default useCommerceCart as UseCart<typeof handler>
|
export default useCommerceCart as UseCart<typeof handler>
|
||||||
@ -22,11 +22,12 @@ export const handler: SWRHook<
|
|||||||
},
|
},
|
||||||
async fetcher({ input: { cartId: checkoutId }, options, fetch }) {
|
async fetcher({ input: { cartId: checkoutId }, options, fetch }) {
|
||||||
let checkout
|
let checkout
|
||||||
|
|
||||||
if (checkoutId) {
|
if (checkoutId) {
|
||||||
const data = await fetch({
|
const data = await fetch({
|
||||||
...options,
|
...options,
|
||||||
variables: {
|
variables: {
|
||||||
checkoutId,
|
checkoutId: checkoutId,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
checkout = data.node
|
checkout = data.node
|
||||||
@ -36,8 +37,7 @@ export const handler: SWRHook<
|
|||||||
checkout = await checkoutCreate(fetch)
|
checkout = await checkoutCreate(fetch)
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Fix this type
|
return checkoutToCart({ checkout })
|
||||||
return checkoutToCart({ checkout } as any)
|
|
||||||
},
|
},
|
||||||
useHook: ({ useData }) => (input) => {
|
useHook: ({ useData }) => (input) => {
|
||||||
const response = useData({
|
const response = useData({
|
||||||
|
@ -1,23 +1,22 @@
|
|||||||
import { useCallback } from 'react'
|
import { useCallback } from 'react'
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
MutationHookContext,
|
MutationHookContext,
|
||||||
HookFetcherContext,
|
HookFetcherContext,
|
||||||
} from '@commerce/utils/types'
|
} from '@commerce/utils/types'
|
||||||
|
import { RemoveCartItemBody } from '@commerce/types'
|
||||||
import { ValidationError } from '@commerce/utils/errors'
|
import { ValidationError } from '@commerce/utils/errors'
|
||||||
|
|
||||||
import useRemoveItem, {
|
import useRemoveItem, {
|
||||||
RemoveItemInput as RemoveItemInputBase,
|
RemoveItemInput as RemoveItemInputBase,
|
||||||
UseRemoveItem,
|
UseRemoveItem,
|
||||||
} from '@commerce/cart/use-remove-item'
|
} from '@commerce/cart/use-remove-item'
|
||||||
|
|
||||||
import useCart from './use-cart'
|
import useCart from './use-cart'
|
||||||
import { checkoutLineItemRemoveMutation, getCheckoutId } from '../utils'
|
import {
|
||||||
import { checkoutToCart } from './utils'
|
checkoutLineItemRemoveMutation,
|
||||||
|
getCheckoutId,
|
||||||
|
checkoutToCart,
|
||||||
|
} from '../utils'
|
||||||
import { Cart, LineItem } from '../types'
|
import { Cart, LineItem } from '../types'
|
||||||
import { Mutation, MutationCheckoutLineItemsRemoveArgs } from '../schema'
|
import { Mutation, MutationCheckoutLineItemsRemoveArgs } from '../schema'
|
||||||
import { RemoveCartItemBody } from '@commerce/types'
|
|
||||||
|
|
||||||
export type RemoveItemFn<T = any> = T extends LineItem
|
export type RemoveItemFn<T = any> = T extends LineItem
|
||||||
? (input?: RemoveItemInput<T>) => Promise<Cart | null>
|
? (input?: RemoveItemInput<T>) => Promise<Cart | null>
|
||||||
|
@ -13,7 +13,7 @@ import useUpdateItem, {
|
|||||||
import useCart from './use-cart'
|
import useCart from './use-cart'
|
||||||
import { handler as removeItemHandler } from './use-remove-item'
|
import { handler as removeItemHandler } from './use-remove-item'
|
||||||
import type { Cart, LineItem, UpdateCartItemBody } from '../types'
|
import type { Cart, LineItem, UpdateCartItemBody } from '../types'
|
||||||
import { checkoutToCart } from './utils'
|
import { checkoutToCart } from '../utils'
|
||||||
import { getCheckoutId, checkoutLineItemUpdateMutation } from '../utils'
|
import { getCheckoutId, checkoutLineItemUpdateMutation } from '../utils'
|
||||||
import { Mutation, MutationCheckoutLineItemsUpdateArgs } from '../schema'
|
import { Mutation, MutationCheckoutLineItemsUpdateArgs } from '../schema'
|
||||||
|
|
||||||
|
@ -1,42 +0,0 @@
|
|||||||
import { Cart } from '../../types'
|
|
||||||
import { CommerceError, ValidationError } from '@commerce/utils/errors'
|
|
||||||
|
|
||||||
import {
|
|
||||||
CheckoutLineItemsAddPayload,
|
|
||||||
CheckoutLineItemsRemovePayload,
|
|
||||||
CheckoutLineItemsUpdatePayload,
|
|
||||||
Maybe,
|
|
||||||
} from '../../schema'
|
|
||||||
import { normalizeCart } from '../../utils'
|
|
||||||
|
|
||||||
export type CheckoutPayload =
|
|
||||||
| CheckoutLineItemsAddPayload
|
|
||||||
| CheckoutLineItemsUpdatePayload
|
|
||||||
| CheckoutLineItemsRemovePayload
|
|
||||||
|
|
||||||
const checkoutToCart = (checkoutPayload?: Maybe<CheckoutPayload>): Cart => {
|
|
||||||
if (!checkoutPayload) {
|
|
||||||
throw new CommerceError({
|
|
||||||
message: 'Invalid response from Shopify',
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const checkout = checkoutPayload?.checkout
|
|
||||||
const userErrors = checkoutPayload?.userErrors
|
|
||||||
|
|
||||||
if (userErrors && userErrors.length) {
|
|
||||||
throw new ValidationError({
|
|
||||||
message: userErrors[0].message,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!checkout) {
|
|
||||||
throw new CommerceError({
|
|
||||||
message: 'Invalid response from Shopify',
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return normalizeCart(checkout)
|
|
||||||
}
|
|
||||||
|
|
||||||
export default checkoutToCart
|
|
@ -1,31 +0,0 @@
|
|||||||
import { HookFetcherFn } from '@commerce/utils/types'
|
|
||||||
import { Cart } from '@commerce/types'
|
|
||||||
import { checkoutCreate, checkoutToCart } from '.'
|
|
||||||
import { FetchCartInput } from '@commerce/cart/use-cart'
|
|
||||||
|
|
||||||
const fetcher: HookFetcherFn<Cart | null, FetchCartInput> = async ({
|
|
||||||
options,
|
|
||||||
input: { cartId: checkoutId },
|
|
||||||
fetch,
|
|
||||||
}) => {
|
|
||||||
let checkout
|
|
||||||
|
|
||||||
if (checkoutId) {
|
|
||||||
const data = await fetch({
|
|
||||||
...options,
|
|
||||||
variables: {
|
|
||||||
checkoutId,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
checkout = data.node
|
|
||||||
}
|
|
||||||
|
|
||||||
if (checkout?.completedAt || !checkoutId) {
|
|
||||||
checkout = await checkoutCreate(fetch)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: Fix this type
|
|
||||||
return checkoutToCart({ checkout } as any)
|
|
||||||
}
|
|
||||||
|
|
||||||
export default fetcher
|
|
@ -1,2 +0,0 @@
|
|||||||
export { default as checkoutToCart } from './checkout-to-cart'
|
|
||||||
export { default as checkoutCreate } from './checkout-create'
|
|
@ -2,9 +2,14 @@ import { Fetcher } from '@commerce/utils/types'
|
|||||||
import { API_TOKEN, API_URL } from './const'
|
import { API_TOKEN, API_URL } from './const'
|
||||||
import { handleFetchResponse } from './utils'
|
import { handleFetchResponse } from './utils'
|
||||||
|
|
||||||
const fetcher: Fetcher = async ({ method = 'POST', variables, query }) => {
|
const fetcher: Fetcher = async ({
|
||||||
|
url = API_URL,
|
||||||
|
method = 'POST',
|
||||||
|
variables,
|
||||||
|
query,
|
||||||
|
}) => {
|
||||||
return handleFetchResponse(
|
return handleFetchResponse(
|
||||||
await fetch(API_URL, {
|
await fetch(url, {
|
||||||
method,
|
method,
|
||||||
body: JSON.stringify({ query, variables }),
|
body: JSON.stringify({ query, variables }),
|
||||||
headers: {
|
headers: {
|
||||||
|
@ -28,8 +28,7 @@ export type ShopifyProps = {
|
|||||||
export function CommerceProvider({ children, ...config }: ShopifyProps) {
|
export function CommerceProvider({ children, ...config }: ShopifyProps) {
|
||||||
return (
|
return (
|
||||||
<CoreCommerceProvider
|
<CoreCommerceProvider
|
||||||
// TODO: Fix this type
|
provider={shopifyProvider}
|
||||||
provider={shopifyProvider as any}
|
|
||||||
config={{ ...shopifyConfig, ...config }}
|
config={{ ...shopifyConfig, ...config }}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
|
@ -48,7 +48,8 @@ export const handler: SWRHook<
|
|||||||
edges = data.node?.products?.edges ?? []
|
edges = data.node?.products?.edges ?? []
|
||||||
if (brandId) {
|
if (brandId) {
|
||||||
edges = edges.filter(
|
edges = edges.filter(
|
||||||
({ node: { vendor } }: ProductEdge) => vendor === brandId
|
({ node: { vendor } }: ProductEdge) =>
|
||||||
|
vendor.replace(/\s+/g, '-').toLowerCase() === brandId
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import { SHOPIFY_CHECKOUT_ID_COOKIE, STORE_DOMAIN } from './const'
|
import { SHOPIFY_CHECKOUT_ID_COOKIE } from './const'
|
||||||
|
|
||||||
import { handler as useCart } from './cart/use-cart'
|
import { handler as useCart } from './cart/use-cart'
|
||||||
import { handler as useAddItem } from './cart/use-add-item'
|
import { handler as useAddItem } from './cart/use-add-item'
|
||||||
@ -17,15 +17,11 @@ import fetcher from './fetcher'
|
|||||||
export const shopifyProvider = {
|
export const shopifyProvider = {
|
||||||
locale: 'en-us',
|
locale: 'en-us',
|
||||||
cartCookie: SHOPIFY_CHECKOUT_ID_COOKIE,
|
cartCookie: SHOPIFY_CHECKOUT_ID_COOKIE,
|
||||||
storeDomain: STORE_DOMAIN,
|
|
||||||
fetcher,
|
fetcher,
|
||||||
cart: { useCart, useAddItem, useUpdateItem, useRemoveItem },
|
cart: { useCart, useAddItem, useUpdateItem, useRemoveItem },
|
||||||
customer: { useCustomer },
|
customer: { useCustomer },
|
||||||
products: { useSearch },
|
products: { useSearch },
|
||||||
auth: { useLogin, useLogout, useSignup },
|
auth: { useLogin, useLogout, useSignup },
|
||||||
features: {
|
|
||||||
wishlist: false,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShopifyProvider = typeof shopifyProvider
|
export type ShopifyProvider = typeof shopifyProvider
|
||||||
|
@ -7,13 +7,11 @@ export type ShopifyCheckout = {
|
|||||||
lineItems: CheckoutLineItem[]
|
lineItems: CheckoutLineItem[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Cart extends Core.Cart {
|
export type Cart = Core.Cart & {
|
||||||
id: string
|
|
||||||
lineItems: LineItem[]
|
lineItems: LineItem[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface LineItem extends Core.LineItem {
|
export interface LineItem extends Core.LineItem {
|
||||||
options: any[]
|
options?: any[]
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -1,13 +1,17 @@
|
|||||||
|
import Cookies from 'js-cookie'
|
||||||
|
|
||||||
import {
|
import {
|
||||||
SHOPIFY_CHECKOUT_ID_COOKIE,
|
SHOPIFY_CHECKOUT_ID_COOKIE,
|
||||||
SHOPIFY_CHECKOUT_URL_COOKIE,
|
SHOPIFY_CHECKOUT_URL_COOKIE,
|
||||||
SHOPIFY_COOKIE_EXPIRE,
|
SHOPIFY_COOKIE_EXPIRE,
|
||||||
} from '../../const'
|
} from '../const'
|
||||||
|
|
||||||
import checkoutCreateMutation from '../../utils/mutations/checkout-create'
|
import checkoutCreateMutation from './mutations/checkout-create'
|
||||||
import Cookies from 'js-cookie'
|
import { CheckoutCreatePayload } from '../schema'
|
||||||
|
|
||||||
export const checkoutCreate = async (fetch: any) => {
|
export const checkoutCreate = async (
|
||||||
|
fetch: any
|
||||||
|
): Promise<CheckoutCreatePayload> => {
|
||||||
const data = await fetch({
|
const data = await fetch({
|
||||||
query: checkoutCreateMutation,
|
query: checkoutCreateMutation,
|
||||||
})
|
})
|
||||||
@ -20,7 +24,7 @@ export const checkoutCreate = async (fetch: any) => {
|
|||||||
expires: SHOPIFY_COOKIE_EXPIRE,
|
expires: SHOPIFY_COOKIE_EXPIRE,
|
||||||
}
|
}
|
||||||
Cookies.set(SHOPIFY_CHECKOUT_ID_COOKIE, checkoutId, options)
|
Cookies.set(SHOPIFY_CHECKOUT_ID_COOKIE, checkoutId, options)
|
||||||
Cookies.set(SHOPIFY_CHECKOUT_URL_COOKIE, checkout?.webUrl, options)
|
Cookies.set(SHOPIFY_CHECKOUT_URL_COOKIE, checkout.webUrl, options)
|
||||||
}
|
}
|
||||||
|
|
||||||
return checkout
|
return checkout
|
48
framework/shopify/utils/checkout-to-cart.ts
Normal file
48
framework/shopify/utils/checkout-to-cart.ts
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
import { Cart } from '../types'
|
||||||
|
import { CommerceError } from '@commerce/utils/errors'
|
||||||
|
|
||||||
|
import {
|
||||||
|
CheckoutLineItemsAddPayload,
|
||||||
|
CheckoutLineItemsRemovePayload,
|
||||||
|
CheckoutLineItemsUpdatePayload,
|
||||||
|
CheckoutCreatePayload,
|
||||||
|
CheckoutUserError,
|
||||||
|
Checkout,
|
||||||
|
Maybe,
|
||||||
|
} from '../schema'
|
||||||
|
|
||||||
|
import { normalizeCart } from './normalize'
|
||||||
|
import throwUserErrors from './throw-user-errors'
|
||||||
|
|
||||||
|
export type CheckoutQuery = {
|
||||||
|
checkout: Checkout
|
||||||
|
checkoutUserErrors?: Array<CheckoutUserError>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CheckoutPayload =
|
||||||
|
| CheckoutLineItemsAddPayload
|
||||||
|
| CheckoutLineItemsUpdatePayload
|
||||||
|
| CheckoutLineItemsRemovePayload
|
||||||
|
| CheckoutCreatePayload
|
||||||
|
| CheckoutQuery
|
||||||
|
|
||||||
|
const checkoutToCart = (checkoutPayload?: Maybe<CheckoutPayload>): Cart => {
|
||||||
|
if (!checkoutPayload) {
|
||||||
|
throw new CommerceError({
|
||||||
|
message: 'Missing checkout payload from response',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkout = checkoutPayload?.checkout
|
||||||
|
throwUserErrors(checkoutPayload?.checkoutUserErrors)
|
||||||
|
|
||||||
|
if (!checkout) {
|
||||||
|
throw new CommerceError({
|
||||||
|
message: 'Missing checkout object from response',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return normalizeCart(checkout)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default checkoutToCart
|
@ -1,4 +1,4 @@
|
|||||||
const getSortVariables = (sort?: string, isCategory = false) => {
|
const getSortVariables = (sort?: string, isCategory: boolean = false) => {
|
||||||
let output = {}
|
let output = {}
|
||||||
switch (sort) {
|
switch (sort) {
|
||||||
case 'price-asc':
|
case 'price-asc':
|
||||||
|
@ -2,13 +2,14 @@ import { ShopifyConfig } from '../api'
|
|||||||
import fetchAllProducts from '../api/utils/fetch-all-products'
|
import fetchAllProducts from '../api/utils/fetch-all-products'
|
||||||
import getAllProductVendors from './queries/get-all-product-vendors-query'
|
import getAllProductVendors from './queries/get-all-product-vendors-query'
|
||||||
|
|
||||||
export type BrandNode = {
|
export type Brand = {
|
||||||
|
entityId: string
|
||||||
name: string
|
name: string
|
||||||
path: string
|
path: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type BrandEdge = {
|
export type BrandEdge = {
|
||||||
node: BrandNode
|
node: Brand
|
||||||
}
|
}
|
||||||
|
|
||||||
export type Brands = BrandEdge[]
|
export type Brands = BrandEdge[]
|
||||||
@ -24,13 +25,16 @@ const getVendors = async (config: ShopifyConfig): Promise<BrandEdge[]> => {
|
|||||||
|
|
||||||
let vendorsStrings = vendors.map(({ node: { vendor } }) => vendor)
|
let vendorsStrings = vendors.map(({ node: { vendor } }) => vendor)
|
||||||
|
|
||||||
return [...new Set(vendorsStrings)].map((v) => ({
|
return [...new Set(vendorsStrings)].map((v) => {
|
||||||
|
const id = v.replace(/\s+/g, '-').toLowerCase()
|
||||||
|
return {
|
||||||
node: {
|
node: {
|
||||||
entityId: v,
|
entityId: id,
|
||||||
name: v,
|
name: v,
|
||||||
path: `brands/${v}`,
|
path: `brands/${id}`,
|
||||||
},
|
},
|
||||||
}))
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export default getVendors
|
export default getVendors
|
||||||
|
30
framework/shopify/utils/handle-account-activation.ts
Normal file
30
framework/shopify/utils/handle-account-activation.ts
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
import { FetcherOptions } from '@commerce/utils/types'
|
||||||
|
import throwUserErrors from './throw-user-errors'
|
||||||
|
|
||||||
|
import {
|
||||||
|
MutationCustomerActivateArgs,
|
||||||
|
MutationCustomerActivateByUrlArgs,
|
||||||
|
} from '../schema'
|
||||||
|
import { Mutation } from '../schema'
|
||||||
|
import { customerActivateByUrlMutation } from './mutations'
|
||||||
|
|
||||||
|
const handleAccountActivation = async (
|
||||||
|
fetch: <T = any, B = Body>(options: FetcherOptions<B>) => Promise<T>,
|
||||||
|
input: MutationCustomerActivateByUrlArgs
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const { customerActivateByUrl } = await fetch<
|
||||||
|
Mutation,
|
||||||
|
MutationCustomerActivateArgs
|
||||||
|
>({
|
||||||
|
query: customerActivateByUrlMutation,
|
||||||
|
variables: {
|
||||||
|
input,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
throwUserErrors(customerActivateByUrl?.customerUserErrors)
|
||||||
|
} catch (error) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default handleAccountActivation
|
@ -1,30 +1,12 @@
|
|||||||
import { ValidationError } from '@commerce/utils/errors'
|
import { FetcherOptions } from '@commerce/utils/types'
|
||||||
|
import { CustomerAccessTokenCreateInput } from '../schema'
|
||||||
import { setCustomerToken } from './customer-token'
|
import { setCustomerToken } from './customer-token'
|
||||||
|
import { customerAccessTokenCreateMutation } from './mutations'
|
||||||
const getErrorMessage = ({
|
import throwUserErrors from './throw-user-errors'
|
||||||
code,
|
|
||||||
message,
|
|
||||||
}: {
|
|
||||||
code: string
|
|
||||||
message: string
|
|
||||||
}) => {
|
|
||||||
switch (code) {
|
|
||||||
case 'UNIDENTIFIED_CUSTOMER':
|
|
||||||
message = 'Cannot find an account that matches the provided credentials'
|
|
||||||
break
|
|
||||||
}
|
|
||||||
return message
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleLogin = (data: any) => {
|
const handleLogin = (data: any) => {
|
||||||
const response = data.customerAccessTokenCreate
|
const response = data.customerAccessTokenCreate
|
||||||
const errors = response?.customerUserErrors
|
throwUserErrors(response?.customerUserErrors)
|
||||||
|
|
||||||
if (errors && errors.length) {
|
|
||||||
throw new ValidationError({
|
|
||||||
message: getErrorMessage(errors[0]),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const customerAccessToken = response?.customerAccessToken
|
const customerAccessToken = response?.customerAccessToken
|
||||||
const accessToken = customerAccessToken?.accessToken
|
const accessToken = customerAccessToken?.accessToken
|
||||||
@ -36,4 +18,19 @@ const handleLogin = (data: any) => {
|
|||||||
return customerAccessToken
|
return customerAccessToken
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const handleAutomaticLogin = async (
|
||||||
|
fetch: <T = any, B = Body>(options: FetcherOptions<B>) => Promise<T>,
|
||||||
|
input: CustomerAccessTokenCreateInput
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const loginData = await fetch({
|
||||||
|
query: customerAccessTokenCreateMutation,
|
||||||
|
variables: {
|
||||||
|
input,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
handleLogin(loginData)
|
||||||
|
} catch (error) {}
|
||||||
|
}
|
||||||
|
|
||||||
export default handleLogin
|
export default handleLogin
|
||||||
|
@ -4,6 +4,11 @@ export { default as getSortVariables } from './get-sort-variables'
|
|||||||
export { default as getVendors } from './get-vendors'
|
export { default as getVendors } from './get-vendors'
|
||||||
export { default as getCategories } from './get-categories'
|
export { default as getCategories } from './get-categories'
|
||||||
export { default as getCheckoutId } from './get-checkout-id'
|
export { default as getCheckoutId } from './get-checkout-id'
|
||||||
|
export { default as checkoutCreate } from './checkout-create'
|
||||||
|
export { default as checkoutToCart } from './checkout-to-cart'
|
||||||
|
export { default as handleLogin, handleAutomaticLogin } from './handle-login'
|
||||||
|
export { default as handleAccountActivation } from './handle-account-activation'
|
||||||
|
export { default as throwUserErrors } from './throw-user-errors'
|
||||||
export * from './queries'
|
export * from './queries'
|
||||||
export * from './mutations'
|
export * from './mutations'
|
||||||
export * from './normalize'
|
export * from './normalize'
|
||||||
|
@ -3,9 +3,10 @@ import { checkoutDetailsFragment } from '../queries/get-checkout-query'
|
|||||||
const checkoutCreateMutation = /* GraphQL */ `
|
const checkoutCreateMutation = /* GraphQL */ `
|
||||||
mutation {
|
mutation {
|
||||||
checkoutCreate(input: {}) {
|
checkoutCreate(input: {}) {
|
||||||
userErrors {
|
checkoutUserErrors {
|
||||||
message
|
code
|
||||||
field
|
field
|
||||||
|
message
|
||||||
}
|
}
|
||||||
checkout {
|
checkout {
|
||||||
${checkoutDetailsFragment}
|
${checkoutDetailsFragment}
|
||||||
|
@ -3,9 +3,10 @@ import { checkoutDetailsFragment } from '../queries/get-checkout-query'
|
|||||||
const checkoutLineItemAddMutation = /* GraphQL */ `
|
const checkoutLineItemAddMutation = /* GraphQL */ `
|
||||||
mutation($checkoutId: ID!, $lineItems: [CheckoutLineItemInput!]!) {
|
mutation($checkoutId: ID!, $lineItems: [CheckoutLineItemInput!]!) {
|
||||||
checkoutLineItemsAdd(checkoutId: $checkoutId, lineItems: $lineItems) {
|
checkoutLineItemsAdd(checkoutId: $checkoutId, lineItems: $lineItems) {
|
||||||
userErrors {
|
checkoutUserErrors {
|
||||||
message
|
code
|
||||||
field
|
field
|
||||||
|
message
|
||||||
}
|
}
|
||||||
checkout {
|
checkout {
|
||||||
${checkoutDetailsFragment}
|
${checkoutDetailsFragment}
|
||||||
|
@ -6,9 +6,10 @@ const checkoutLineItemRemoveMutation = /* GraphQL */ `
|
|||||||
checkoutId: $checkoutId
|
checkoutId: $checkoutId
|
||||||
lineItemIds: $lineItemIds
|
lineItemIds: $lineItemIds
|
||||||
) {
|
) {
|
||||||
userErrors {
|
checkoutUserErrors {
|
||||||
message
|
code
|
||||||
field
|
field
|
||||||
|
message
|
||||||
}
|
}
|
||||||
checkout {
|
checkout {
|
||||||
${checkoutDetailsFragment}
|
${checkoutDetailsFragment}
|
||||||
|
@ -3,9 +3,10 @@ import { checkoutDetailsFragment } from '../queries/get-checkout-query'
|
|||||||
const checkoutLineItemUpdateMutation = /* GraphQL */ `
|
const checkoutLineItemUpdateMutation = /* GraphQL */ `
|
||||||
mutation($checkoutId: ID!, $lineItems: [CheckoutLineItemUpdateInput!]!) {
|
mutation($checkoutId: ID!, $lineItems: [CheckoutLineItemUpdateInput!]!) {
|
||||||
checkoutLineItemsUpdate(checkoutId: $checkoutId, lineItems: $lineItems) {
|
checkoutLineItemsUpdate(checkoutId: $checkoutId, lineItems: $lineItems) {
|
||||||
userErrors {
|
checkoutUserErrors {
|
||||||
message
|
code
|
||||||
field
|
field
|
||||||
|
message
|
||||||
}
|
}
|
||||||
checkout {
|
checkout {
|
||||||
${checkoutDetailsFragment}
|
${checkoutDetailsFragment}
|
||||||
|
@ -0,0 +1,19 @@
|
|||||||
|
const customerActivateByUrlMutation = /* GraphQL */ `
|
||||||
|
mutation customerActivateByUrl($activationUrl: URL!, $password: String!) {
|
||||||
|
customerActivateByUrl(activationUrl: $activationUrl, password: $password) {
|
||||||
|
customer {
|
||||||
|
id
|
||||||
|
}
|
||||||
|
customerAccessToken {
|
||||||
|
accessToken
|
||||||
|
expiresAt
|
||||||
|
}
|
||||||
|
customerUserErrors {
|
||||||
|
code
|
||||||
|
field
|
||||||
|
message
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`
|
||||||
|
export default customerActivateByUrlMutation
|
19
framework/shopify/utils/mutations/customer-activate.ts
Normal file
19
framework/shopify/utils/mutations/customer-activate.ts
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
const customerActivateMutation = /* GraphQL */ `
|
||||||
|
mutation customerActivate($id: ID!, $input: CustomerActivateInput!) {
|
||||||
|
customerActivate(id: $id, input: $input) {
|
||||||
|
customer {
|
||||||
|
id
|
||||||
|
}
|
||||||
|
customerAccessToken {
|
||||||
|
accessToken
|
||||||
|
expiresAt
|
||||||
|
}
|
||||||
|
customerUserErrors {
|
||||||
|
code
|
||||||
|
field
|
||||||
|
message
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`
|
||||||
|
export default customerActivateMutation
|
@ -5,3 +5,5 @@ export { default as checkoutLineItemUpdateMutation } from './checkout-line-item-
|
|||||||
export { default as checkoutLineItemRemoveMutation } from './checkout-line-item-remove'
|
export { default as checkoutLineItemRemoveMutation } from './checkout-line-item-remove'
|
||||||
export { default as customerAccessTokenCreateMutation } from './customer-access-token-create'
|
export { default as customerAccessTokenCreateMutation } from './customer-access-token-create'
|
||||||
export { default as customerAccessTokenDeleteMutation } from './customer-access-token-delete'
|
export { default as customerAccessTokenDeleteMutation } from './customer-access-token-delete'
|
||||||
|
export { default as customerActivateMutation } from './customer-activate'
|
||||||
|
export { default as customerActivateByUrlMutation } from './customer-activate-by-url'
|
||||||
|
@ -33,7 +33,7 @@ const normalizeProductOption = ({
|
|||||||
let output: any = {
|
let output: any = {
|
||||||
label: value,
|
label: value,
|
||||||
}
|
}
|
||||||
if (displayName === 'Color') {
|
if (displayName.match(/colou?r/gi)) {
|
||||||
output = {
|
output = {
|
||||||
...output,
|
...output,
|
||||||
hexColors: [value],
|
hexColors: [value],
|
||||||
@ -54,21 +54,24 @@ const normalizeProductVariants = ({ edges }: ProductVariantConnection) => {
|
|||||||
return edges?.map(
|
return edges?.map(
|
||||||
({
|
({
|
||||||
node: { id, selectedOptions, sku, title, priceV2, compareAtPriceV2 },
|
node: { id, selectedOptions, sku, title, priceV2, compareAtPriceV2 },
|
||||||
}) => ({
|
}) => {
|
||||||
|
return {
|
||||||
id,
|
id,
|
||||||
name: title,
|
name: title,
|
||||||
sku: sku ?? id,
|
sku: sku ?? id,
|
||||||
price: +priceV2.amount,
|
price: +priceV2.amount,
|
||||||
listPrice: +compareAtPriceV2?.amount,
|
listPrice: +compareAtPriceV2?.amount,
|
||||||
requiresShipping: true,
|
requiresShipping: true,
|
||||||
options: selectedOptions.map(({ name, value }: SelectedOption) =>
|
options: selectedOptions.map(({ name, value }: SelectedOption) => {
|
||||||
normalizeProductOption({
|
const options = normalizeProductOption({
|
||||||
id,
|
id,
|
||||||
name,
|
name,
|
||||||
values: [value],
|
values: [value],
|
||||||
})
|
})
|
||||||
),
|
return options
|
||||||
})
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -96,7 +99,11 @@ export function normalizeProduct(productNode: ShopifyProduct): Product {
|
|||||||
price: money(priceRange?.minVariantPrice),
|
price: money(priceRange?.minVariantPrice),
|
||||||
images: normalizeProductImages(images),
|
images: normalizeProductImages(images),
|
||||||
variants: variants ? normalizeProductVariants(variants) : [],
|
variants: variants ? normalizeProductVariants(variants) : [],
|
||||||
options: options ? options.map((o) => normalizeProductOption(o)) : [],
|
options: options
|
||||||
|
? options
|
||||||
|
.filter((o) => o.name !== 'Title') // By default Shopify adds a 'Title' name when there's only one option. We don't need it. https://community.shopify.com/c/Shopify-APIs-SDKs/Adding-new-product-variant-is-automatically-adding-quot-Default/td-p/358095
|
||||||
|
.map((o) => normalizeProductOption(o))
|
||||||
|
: [],
|
||||||
...rest,
|
...rest,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -122,7 +129,7 @@ export function normalizeCart(checkout: Checkout): Cart {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function normalizeLineItem({
|
function normalizeLineItem({
|
||||||
node: { id, title, variant, quantity },
|
node: { id, title, variant, quantity, ...rest },
|
||||||
}: CheckoutLineItemEdge): LineItem {
|
}: CheckoutLineItemEdge): LineItem {
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
@ -135,15 +142,19 @@ function normalizeLineItem({
|
|||||||
sku: variant?.sku ?? '',
|
sku: variant?.sku ?? '',
|
||||||
name: variant?.title!,
|
name: variant?.title!,
|
||||||
image: {
|
image: {
|
||||||
url: variant?.image?.originalSrc,
|
url: variant?.image?.originalSrc ?? '/product-img-placeholder.svg',
|
||||||
},
|
},
|
||||||
requiresShipping: variant?.requiresShipping ?? false,
|
requiresShipping: variant?.requiresShipping ?? false,
|
||||||
price: variant?.priceV2?.amount,
|
price: variant?.priceV2?.amount,
|
||||||
listPrice: variant?.compareAtPriceV2?.amount,
|
listPrice: variant?.compareAtPriceV2?.amount,
|
||||||
},
|
},
|
||||||
path: '',
|
path: String(variant?.product?.handle),
|
||||||
discounts: [],
|
discounts: [],
|
||||||
options: [
|
options:
|
||||||
|
// By default Shopify adds a default variant with default names, we're removing it. https://community.shopify.com/c/Shopify-APIs-SDKs/Adding-new-product-variant-is-automatically-adding-quot-Default/td-p/358095
|
||||||
|
variant?.title == 'Default Title'
|
||||||
|
? []
|
||||||
|
: [
|
||||||
{
|
{
|
||||||
value: variant?.title,
|
value: variant?.title,
|
||||||
},
|
},
|
||||||
|
@ -43,6 +43,9 @@ export const checkoutDetailsFragment = `
|
|||||||
amount
|
amount
|
||||||
currencyCode
|
currencyCode
|
||||||
}
|
}
|
||||||
|
product {
|
||||||
|
handle
|
||||||
|
}
|
||||||
}
|
}
|
||||||
quantity
|
quantity
|
||||||
}
|
}
|
||||||
|
@ -1,13 +0,0 @@
|
|||||||
export const getCheckoutIdFromStorage = (token: string) => {
|
|
||||||
if (window && window.sessionStorage) {
|
|
||||||
return window.sessionStorage.getItem(token)
|
|
||||||
}
|
|
||||||
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
export const setCheckoutIdInStorage = (token: string, id: string | number) => {
|
|
||||||
if (window && window.sessionStorage) {
|
|
||||||
return window.sessionStorage.setItem(token, id + '')
|
|
||||||
}
|
|
||||||
}
|
|
38
framework/shopify/utils/throw-user-errors.ts
Normal file
38
framework/shopify/utils/throw-user-errors.ts
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
import { ValidationError } from '@commerce/utils/errors'
|
||||||
|
|
||||||
|
import {
|
||||||
|
CheckoutErrorCode,
|
||||||
|
CheckoutUserError,
|
||||||
|
CustomerErrorCode,
|
||||||
|
CustomerUserError,
|
||||||
|
} from '../schema'
|
||||||
|
|
||||||
|
export type UserErrors = Array<CheckoutUserError | CustomerUserError>
|
||||||
|
|
||||||
|
export type UserErrorCode =
|
||||||
|
| CustomerErrorCode
|
||||||
|
| CheckoutErrorCode
|
||||||
|
| null
|
||||||
|
| undefined
|
||||||
|
|
||||||
|
const getCustomMessage = (code: UserErrorCode, message: string) => {
|
||||||
|
switch (code) {
|
||||||
|
case 'UNIDENTIFIED_CUSTOMER':
|
||||||
|
message = 'Cannot find an account that matches the provided credentials'
|
||||||
|
break
|
||||||
|
}
|
||||||
|
return message
|
||||||
|
}
|
||||||
|
|
||||||
|
export const throwUserErrors = (errors?: UserErrors) => {
|
||||||
|
if (errors && errors.length) {
|
||||||
|
throw new ValidationError({
|
||||||
|
errors: errors.map(({ code, message }) => ({
|
||||||
|
code: code ?? 'validation_error',
|
||||||
|
message: getCustomMessage(code, message),
|
||||||
|
})),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default throwUserErrors
|
@ -25,8 +25,7 @@ export async function getStaticProps({
|
|||||||
const pageItem = pages.find((p) => (p.url ? getSlug(p.url) === slug : false))
|
const pageItem = pages.find((p) => (p.url ? getSlug(p.url) === slug : false))
|
||||||
const data =
|
const data =
|
||||||
pageItem &&
|
pageItem &&
|
||||||
// TODO: Shopify - Fix this type
|
(await getPage({ variables: { id: pageItem.id! }, config, preview }))
|
||||||
(await getPage({ variables: { id: pageItem.id! } as any, config, preview }))
|
|
||||||
const page = data?.page
|
const page = data?.page
|
||||||
|
|
||||||
if (!page) {
|
if (!page) {
|
||||||
|
@ -75,10 +75,8 @@ export default function Search({
|
|||||||
|
|
||||||
const { data } = useSearch({
|
const { data } = useSearch({
|
||||||
search: typeof q === 'string' ? q : '',
|
search: typeof q === 'string' ? q : '',
|
||||||
// TODO: Shopify - Fix this type
|
categoryId: activeCategory?.entityId,
|
||||||
categoryId: activeCategory?.entityId as any,
|
brandId: activeBrand?.entityId,
|
||||||
// TODO: Shopify - Fix this type
|
|
||||||
brandId: (activeBrand as any)?.entityId,
|
|
||||||
sort: typeof sort === 'string' ? sort : '',
|
sort: typeof sort === 'string' ? sort : '',
|
||||||
})
|
})
|
||||||
|
|
||||||
|
@ -22,8 +22,8 @@
|
|||||||
"@components/*": ["components/*"],
|
"@components/*": ["components/*"],
|
||||||
"@commerce": ["framework/commerce"],
|
"@commerce": ["framework/commerce"],
|
||||||
"@commerce/*": ["framework/commerce/*"],
|
"@commerce/*": ["framework/commerce/*"],
|
||||||
"@framework": ["framework/bigcommerce"],
|
"@framework": ["framework/shopify"],
|
||||||
"@framework/*": ["framework/bigcommerce/*"]
|
"@framework/*": ["framework/shopify/*"]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"include": ["next-env.d.ts", "**/*.d.ts", "**/*.ts", "**/*.tsx", "**/*.js"],
|
"include": ["next-env.d.ts", "**/*.d.ts", "**/*.ts", "**/*.tsx", "**/*.js"],
|
||||||
|
Loading…
x
Reference in New Issue
Block a user