mirror of
https://github.com/vercel/commerce.git
synced 2025-06-19 05:31:22 +00:00
Merge branch 'master' into enhance-ada
This commit is contained in:
commit
5c7ce45e1f
@ -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 () => {
|
||||||
@ -133,7 +136,7 @@ const ProductView: FC<Props> = ({ product }) => {
|
|||||||
))}
|
))}
|
||||||
|
|
||||||
<div className="pb-14 break-words w-full max-w-xl">
|
<div className="pb-14 break-words w-full max-w-xl">
|
||||||
<Text html={product.description} />
|
<Text html={product.descriptionHtml || product.description} />
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<div>
|
<div>
|
||||||
@ -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) => {
|
||||||
|
@ -1 +0,0 @@
|
|||||||
# Roadmap
|
|
@ -163,6 +163,7 @@ interface Entity {
|
|||||||
export interface Product extends Entity {
|
export interface Product extends Entity {
|
||||||
name: string
|
name: string
|
||||||
description: string
|
description: string
|
||||||
|
descriptionHtml?: string
|
||||||
slug?: string
|
slug?: string
|
||||||
path?: string
|
path?: string
|
||||||
images: ProductImage[]
|
images: ProductImage[]
|
||||||
|
@ -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}
|
||||||
|
@ -21,11 +21,10 @@ const getProduct = async (options: {
|
|||||||
const { data }: GraphQLFetcherResult = await config.fetch(getProductQuery, {
|
const { data }: GraphQLFetcherResult = await config.fetch(getProductQuery, {
|
||||||
variables,
|
variables,
|
||||||
})
|
})
|
||||||
|
const { productByHandle } = data
|
||||||
const { productByHandle: product } = data
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
product: product ? normalizeProduct(product) : null,
|
product: productByHandle ? normalizeProduct(productByHandle) : null,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -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
|
||||||
})
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -80,6 +83,7 @@ export function normalizeProduct(productNode: ShopifyProduct): Product {
|
|||||||
images,
|
images,
|
||||||
variants,
|
variants,
|
||||||
description,
|
description,
|
||||||
|
descriptionHtml,
|
||||||
handle,
|
handle,
|
||||||
priceRange,
|
priceRange,
|
||||||
options,
|
options,
|
||||||
@ -90,13 +94,18 @@ export function normalizeProduct(productNode: ShopifyProduct): Product {
|
|||||||
id,
|
id,
|
||||||
name,
|
name,
|
||||||
vendor,
|
vendor,
|
||||||
description,
|
|
||||||
path: `/${handle}`,
|
path: `/${handle}`,
|
||||||
slug: handle?.replace(/^\/+|\/+$/g, ''),
|
slug: handle?.replace(/^\/+|\/+$/g, ''),
|
||||||
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))
|
||||||
|
: [],
|
||||||
|
...(description && { description }),
|
||||||
|
...(descriptionHtml && { descriptionHtml }),
|
||||||
...rest,
|
...rest,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -122,7 +131,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 +144,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,
|
||||||
},
|
},
|
||||||
|
@ -9,7 +9,6 @@ edges {
|
|||||||
title
|
title
|
||||||
vendor
|
vendor
|
||||||
handle
|
handle
|
||||||
description
|
|
||||||
priceRange {
|
priceRange {
|
||||||
minVariantPrice {
|
minVariantPrice {
|
||||||
amount
|
amount
|
||||||
|
@ -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