mirror of
https://github.com/vercel/commerce.git
synced 2025-04-13 14:55:54 +00:00
Implement Shopify Provider
This commit is contained in:
parent
c06d9dae3a
commit
14c3f961b3
@ -122,7 +122,7 @@ const CartSidebarView: FC = () => {
|
||||
<span>{total}</span>
|
||||
</div>
|
||||
</div>
|
||||
<Button href="/checkout" Component="a" width="100%">
|
||||
<Button href={data.webUrl} Component="a" width="100%">
|
||||
Proceed to Checkout
|
||||
</Button>
|
||||
</div>
|
||||
|
@ -19,7 +19,7 @@ const Head: FC<Props> = ({ categories, brands, products = [] }) => {
|
||||
<ul className="mb-10">
|
||||
<li className="py-1 text-base font-bold tracking-wide">
|
||||
<Link href={getCategoryPath('')}>
|
||||
<a>All Categories</a>
|
||||
<a>All Collections</a>
|
||||
</Link>
|
||||
</li>
|
||||
{categories.map((cat: any) => (
|
||||
@ -30,20 +30,6 @@ const Head: FC<Props> = ({ categories, brands, products = [] }) => {
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<ul className="">
|
||||
<li className="py-1 text-base font-bold tracking-wide">
|
||||
<Link href={getDesignerPath('')}>
|
||||
<a>All Designers</a>
|
||||
</Link>
|
||||
</li>
|
||||
{brands.flatMap(({ node }: any) => (
|
||||
<li key={node.path} className="py-1 text-accents-8 text-base">
|
||||
<Link href={getDesignerPath(node.path)}>
|
||||
<a>{node.name}</a>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
|
@ -25,6 +25,9 @@ const Navbar: FC = () => (
|
||||
<Link href="/search?q=accessories">
|
||||
<a className={s.link}>Accessories</a>
|
||||
</Link>
|
||||
<Link href="/search?q=shoes">
|
||||
<a className={s.link}>Shoes</a>
|
||||
</Link>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
|
@ -132,5 +132,5 @@
|
||||
}
|
||||
|
||||
.productImage {
|
||||
@apply transform transition-transform duration-500 object-cover scale-120;
|
||||
@apply transform transition-transform duration-500 object-cover;
|
||||
}
|
||||
|
@ -329,6 +329,7 @@ const SearchPage = ({ searchString, category, brand, sortStr }) => {
|
||||
const { data } = useSearch({
|
||||
search: searchString || '',
|
||||
categoryId: category?.entityId,
|
||||
categorySlug: category?.slug,
|
||||
brandId: brand?.entityId,
|
||||
sort: sortStr || '',
|
||||
})
|
||||
|
260
framework/shopify/README.md
Normal file
260
framework/shopify/README.md
Normal file
@ -0,0 +1,260 @@
|
||||
## Table of Contents
|
||||
|
||||
- [Getting Started](#getting-started)
|
||||
- [Modifications](#modifications)
|
||||
- [Adding item to Cart](#adding-item-to-cart)
|
||||
- [Proceed to Checkout](#proceed-to-checkout)
|
||||
- [General Usage](#general-usage)
|
||||
- [CommerceProvider](#commerceprovider)
|
||||
- [useCommerce](#usecommerce)
|
||||
- [Hooks](#hooks)
|
||||
- [usePrice](#useprice)
|
||||
- [useAddItem](#useadditem)
|
||||
- [useRemoveItem](#useremoveitem)
|
||||
- [useUpdateItem](#useupdateitem)
|
||||
- [APIs](#apis)
|
||||
- [getProduct](#getproduct)
|
||||
- [getAllProducts](#getallproducts)
|
||||
- [getAllCollections](#getallcollections)
|
||||
- [getAllPages](#getallpages)
|
||||
|
||||
# Shopify Storefront Data Hooks
|
||||
|
||||
Collection of hooks and data fetching functions to integrate Shopify in a React application. Designed to work with [Next.js Commerce](https://demo.vercel.store/).
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. Install dependencies:
|
||||
|
||||
```
|
||||
yarn install shopify-buy
|
||||
yarn install -D @types/shopify-buy
|
||||
```
|
||||
|
||||
3. Environment variables need to be set:
|
||||
|
||||
```
|
||||
SHOPIFY_STORE_DOMAIN=
|
||||
SHOPIFY_STOREFRONT_ACCESS_TOKEN=
|
||||
NEXT_PUBLIC_SHOPIFY_STORE_DOMAIN=
|
||||
NEXT_PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN=
|
||||
```
|
||||
|
||||
4. Point the framework to `shopify` by updating `tsconfig.json`:
|
||||
|
||||
```
|
||||
"@framework/*": ["framework/shopify/*"],
|
||||
"@framework": ["framework/shopify"]
|
||||
```
|
||||
|
||||
### Modifications
|
||||
|
||||
These modifications are temporarily until contributions are made to remove them.
|
||||
|
||||
#### Adding item to Cart
|
||||
|
||||
```js
|
||||
// components/product/ProductView/ProductView.tsx
|
||||
const ProductView: FC<Props> = ({ product }) => {
|
||||
const addToCart = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
await addItem({
|
||||
productId: product.id,
|
||||
variantId: variant ? variant.id : product.variants[0].id,
|
||||
})
|
||||
openSidebar()
|
||||
setLoading(false)
|
||||
} catch (err) {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Proceed to Checkout
|
||||
|
||||
```js
|
||||
// components/cart/CartSidebarView/CartSidebarView.tsx
|
||||
import { useCommerce } from '@framework'
|
||||
|
||||
const CartSidebarView: FC = () => {
|
||||
const { checkout } = useCommerce()
|
||||
return (
|
||||
<Button href={checkout.webUrl} Component="a" width="100%">
|
||||
Proceed to Checkout
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## General Usage
|
||||
|
||||
### CommerceProvider
|
||||
|
||||
Provider component that creates the commerce context for children.
|
||||
|
||||
```js
|
||||
import { CommerceProvider } from '@framework'
|
||||
|
||||
const App = ({ children }) => {
|
||||
return <CommerceProvider locale={locale}>{children}</CommerceProvider>
|
||||
}
|
||||
|
||||
export default App
|
||||
```
|
||||
|
||||
### useCommerce
|
||||
|
||||
Returns the configs that are defined in the nearest `CommerceProvider`. Also provides access to Shopify's `checkout` and `shop`.
|
||||
|
||||
```js
|
||||
import { useCommerce } from 'nextjs-commerce-shopify'
|
||||
|
||||
const { checkout, shop } = useCommerce()
|
||||
```
|
||||
|
||||
- `checkout`: The information required to checkout items and pay ([Documentation](https://shopify.dev/docs/storefront-api/reference/checkouts/checkout)).
|
||||
- `shop`: Represents a collection of the general settings and information about the shop ([Documentation](https://shopify.dev/docs/storefront-api/reference/online-store/shop/index)).
|
||||
|
||||
## Hooks
|
||||
|
||||
### usePrice
|
||||
|
||||
Display the product variant price according to currency and locale.
|
||||
|
||||
```js
|
||||
import usePrice from '@framework/product/use-price'
|
||||
|
||||
const { price } = usePrice({
|
||||
amount,
|
||||
})
|
||||
```
|
||||
|
||||
Takes in either `amount` or `variant`:
|
||||
|
||||
- `amount`: A price value for a particular item if the amount is known.
|
||||
- `variant`: A shopify product variant. Price will be extracted from the variant.
|
||||
|
||||
### useAddItem
|
||||
|
||||
```js
|
||||
import { useAddItem } from '@framework/cart'
|
||||
|
||||
const AddToCartButton = ({ variantId, quantity }) => {
|
||||
const addItem = useAddItem()
|
||||
|
||||
const addToCart = async () => {
|
||||
await addItem({
|
||||
variantId,
|
||||
})
|
||||
}
|
||||
|
||||
return <button onClick={addToCart}>Add To Cart</button>
|
||||
}
|
||||
```
|
||||
|
||||
### useRemoveItem
|
||||
|
||||
```js
|
||||
import { useRemoveItem } from '@framework/cart'
|
||||
|
||||
const RemoveButton = ({ item }) => {
|
||||
const removeItem = useRemoveItem()
|
||||
|
||||
const handleRemove = async () => {
|
||||
await removeItem({ id: item.id })
|
||||
}
|
||||
|
||||
return <button onClick={handleRemove}>Remove</button>
|
||||
}
|
||||
```
|
||||
|
||||
### useUpdateItem
|
||||
|
||||
```js
|
||||
import { useUpdateItem } from '@framework/cart'
|
||||
|
||||
const CartItem = ({ item }) => {
|
||||
const [quantity, setQuantity] = useState(item.quantity)
|
||||
const updateItem = useUpdateItem(item)
|
||||
|
||||
const updateQuantity = async (e) => {
|
||||
const val = e.target.value
|
||||
await updateItem({ quantity: val })
|
||||
}
|
||||
|
||||
return (
|
||||
<input
|
||||
type="number"
|
||||
max={99}
|
||||
min={0}
|
||||
value={quantity}
|
||||
onChange={updateQuantity}
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## APIs
|
||||
|
||||
Collections of APIs to fetch data from a Shopify store.
|
||||
|
||||
The data is fetched using the [Shopify JavaScript Buy SDK](https://github.com/Shopify/js-buy-sdk#readme). Read the [Shopify Storefront API reference](https://shopify.dev/docs/storefront-api/reference) for more information.
|
||||
|
||||
### getProduct
|
||||
|
||||
Get a single product by its `handle`.
|
||||
|
||||
```js
|
||||
import getProduct from '@framework/product/get-product'
|
||||
import { getConfig } from '@framework/api'
|
||||
|
||||
const config = getConfig()
|
||||
|
||||
const product = await getProduct({
|
||||
variables: { slug },
|
||||
config,
|
||||
})
|
||||
```
|
||||
|
||||
### getAllProducts
|
||||
|
||||
```js
|
||||
import getAllProducts from '@framework/product/get-all-products'
|
||||
import { getConfig } from '@framework/api'
|
||||
|
||||
const config = getConfig()
|
||||
|
||||
const { products } = await getAllProducts({
|
||||
variables: { first: 12 },
|
||||
config,
|
||||
})
|
||||
```
|
||||
|
||||
### getAllCollections
|
||||
|
||||
```js
|
||||
import getAllCollections from '@framework/product/get-all-collections'
|
||||
import { getConfig } from '@framework/api'
|
||||
|
||||
const config = getConfig()
|
||||
|
||||
const collections = await getAllCollections({
|
||||
config,
|
||||
})
|
||||
```
|
||||
|
||||
### getAllPages
|
||||
|
||||
```js
|
||||
import getAllPages from '@framework/common/get-all-pages'
|
||||
import { getConfig } from '@framework/api'
|
||||
|
||||
const config = getConfig()
|
||||
|
||||
const pages = await getAllPages({
|
||||
variables: { first: 12 },
|
||||
config,
|
||||
})
|
||||
```
|
38
framework/shopify/api/customers/handlers/login.ts
Normal file
38
framework/shopify/api/customers/handlers/login.ts
Normal file
@ -0,0 +1,38 @@
|
||||
import { FetcherError } from '@commerce/utils/errors'
|
||||
import type { LoginHandlers } from '../login'
|
||||
|
||||
const loginHandler: LoginHandlers['login'] = async ({
|
||||
res,
|
||||
body: { email, password },
|
||||
config,
|
||||
}) => {
|
||||
if (!(email && password)) {
|
||||
return res.status(400).json({
|
||||
data: null,
|
||||
errors: [{ message: 'Invalid request' }],
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
} catch (error) {
|
||||
// Check if the email and password didn't match an existing account
|
||||
if (error instanceof FetcherError) {
|
||||
return res.status(401).json({
|
||||
data: null,
|
||||
errors: [
|
||||
{
|
||||
message:
|
||||
'Cannot find an account that matches the provided credentials',
|
||||
code: 'invalid_credentials',
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
|
||||
res.status(200).json({ data: null })
|
||||
}
|
||||
|
||||
export default loginHandler
|
1
framework/shopify/api/customers/index.ts
Normal file
1
framework/shopify/api/customers/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export default function () {}
|
1
framework/shopify/api/customers/login.ts
Normal file
1
framework/shopify/api/customers/login.ts
Normal file
@ -0,0 +1 @@
|
||||
export default function () {}
|
1
framework/shopify/api/customers/logout.ts
Normal file
1
framework/shopify/api/customers/logout.ts
Normal file
@ -0,0 +1 @@
|
||||
export default function () {}
|
1
framework/shopify/api/customers/signup.ts
Normal file
1
framework/shopify/api/customers/signup.ts
Normal file
@ -0,0 +1 @@
|
||||
export default function () {}
|
54
framework/shopify/api/index.ts
Normal file
54
framework/shopify/api/index.ts
Normal file
@ -0,0 +1,54 @@
|
||||
import type { CommerceAPIConfig } from '@commerce/api'
|
||||
import fetchGraphqlApi from '../utils/fetch-graphql-api'
|
||||
|
||||
export interface ShopifyConfig extends CommerceAPIConfig {}
|
||||
|
||||
// No I don't like this - will fix it later
|
||||
const API_URL = process.env.NEXT_PUBLIC_SHOPIFY_STORE_DOMAIN
|
||||
const API_TOKEN = process.env.NEXT_PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN
|
||||
|
||||
if (!API_URL) {
|
||||
throw new Error(
|
||||
`The environment variable NEXT_PUBLIC_SHOPIFY_STORE_DOMAIN is missing and it's required to access your store`
|
||||
)
|
||||
}
|
||||
|
||||
if (!API_TOKEN) {
|
||||
throw new Error(
|
||||
`The environment variable NEXT_PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN is missing and it's required to access your store`
|
||||
)
|
||||
}
|
||||
|
||||
export class Config {
|
||||
private config: ShopifyConfig
|
||||
|
||||
constructor(config: ShopifyConfig) {
|
||||
this.config = config
|
||||
}
|
||||
|
||||
getConfig(userConfig: Partial<ShopifyConfig> = {}) {
|
||||
return Object.entries(userConfig).reduce<ShopifyConfig>(
|
||||
(cfg, [key, value]) => Object.assign(cfg, { [key]: value }),
|
||||
{ ...this.config }
|
||||
)
|
||||
}
|
||||
|
||||
setConfig(newConfig: Partial<ShopifyConfig>) {
|
||||
Object.assign(this.config, newConfig)
|
||||
}
|
||||
}
|
||||
|
||||
const config = new Config({
|
||||
commerceUrl: API_URL,
|
||||
apiToken: API_TOKEN,
|
||||
fetch: fetchGraphqlApi,
|
||||
customerCookie: 'SHOP_TOKEN',
|
||||
})
|
||||
|
||||
export function getConfig(userConfig?: Partial<ShopifyConfig>) {
|
||||
return config.getConfig(userConfig)
|
||||
}
|
||||
|
||||
export function setConfig(newConfig: Partial<ShopifyConfig>) {
|
||||
return config.setConfig(newConfig)
|
||||
}
|
2
framework/shopify/api/wishlist/index.tsx
Normal file
2
framework/shopify/api/wishlist/index.tsx
Normal file
@ -0,0 +1,2 @@
|
||||
export type WishlistItem = { product: any; id: number }
|
||||
export default function () {}
|
53
framework/shopify/auth/use-login.tsx
Normal file
53
framework/shopify/auth/use-login.tsx
Normal file
@ -0,0 +1,53 @@
|
||||
import { useCallback } from 'react'
|
||||
import type { HookFetcher } from '@commerce/utils/types'
|
||||
import { CommerceError } from '@commerce/utils/errors'
|
||||
import useCommerceLogin from '@commerce/use-login'
|
||||
import type { LoginBody } from '../api/customers/login'
|
||||
import useCustomer from '../customer/use-customer'
|
||||
|
||||
const defaultOpts = {
|
||||
query: '/api/bigcommerce/customers/login',
|
||||
}
|
||||
|
||||
export type LoginInput = LoginBody
|
||||
|
||||
export const fetcher: HookFetcher<null, LoginBody> = (
|
||||
options,
|
||||
{ email, password },
|
||||
fetch
|
||||
) => {
|
||||
if (!(email && password)) {
|
||||
throw new CommerceError({
|
||||
message:
|
||||
'A first name, last name, email and password are required to login',
|
||||
})
|
||||
}
|
||||
|
||||
return fetch({
|
||||
...defaultOpts,
|
||||
...options,
|
||||
body: { email, password },
|
||||
})
|
||||
}
|
||||
|
||||
export function extendHook(customFetcher: typeof fetcher) {
|
||||
const useLogin = () => {
|
||||
const { revalidate } = useCustomer()
|
||||
const fn = useCommerceLogin<null, LoginInput>(defaultOpts, customFetcher)
|
||||
|
||||
return useCallback(
|
||||
async function login(input: LoginInput) {
|
||||
const data = await fn(input)
|
||||
await revalidate()
|
||||
return data
|
||||
},
|
||||
[fn]
|
||||
)
|
||||
}
|
||||
|
||||
useLogin.extend = extendHook
|
||||
|
||||
return useLogin
|
||||
}
|
||||
|
||||
export default extendHook(fetcher)
|
13
framework/shopify/auth/use-logout.tsx
Normal file
13
framework/shopify/auth/use-logout.tsx
Normal file
@ -0,0 +1,13 @@
|
||||
import { useCallback } from 'react'
|
||||
|
||||
export function emptyHook() {
|
||||
const useEmptyHook = async (options = {}) => {
|
||||
return useCallback(async function () {
|
||||
return Promise.resolve()
|
||||
}, [])
|
||||
}
|
||||
|
||||
return useEmptyHook
|
||||
}
|
||||
|
||||
export default emptyHook
|
13
framework/shopify/auth/use-signup.tsx
Normal file
13
framework/shopify/auth/use-signup.tsx
Normal file
@ -0,0 +1,13 @@
|
||||
import { useCallback } from 'react'
|
||||
|
||||
export function emptyHook() {
|
||||
const useEmptyHook = async (options = {}) => {
|
||||
return useCallback(async function () {
|
||||
return Promise.resolve()
|
||||
}, [])
|
||||
}
|
||||
|
||||
return useEmptyHook
|
||||
}
|
||||
|
||||
export default emptyHook
|
3
framework/shopify/cart/index.ts
Normal file
3
framework/shopify/cart/index.ts
Normal file
@ -0,0 +1,3 @@
|
||||
export { default as useCart } from './use-cart'
|
||||
export { default as useAddItem } from './use-add-item'
|
||||
export { default as useRemoveItem } from './use-remove-item'
|
70
framework/shopify/cart/use-add-item.tsx
Normal file
70
framework/shopify/cart/use-add-item.tsx
Normal file
@ -0,0 +1,70 @@
|
||||
import { useCallback } from 'react'
|
||||
import { CommerceError } from '@commerce/utils/errors'
|
||||
import useCart from './use-cart'
|
||||
import useCartAddItem, {
|
||||
AddItemInput as UseAddItemInput,
|
||||
} from '@commerce/cart/use-add-item'
|
||||
import type { HookFetcher } from '@commerce/utils/types'
|
||||
import type { Cart } from '@commerce/types'
|
||||
import checkoutLineItemAddMutation from '../utils/mutations/checkout-line-item-add'
|
||||
import getCheckoutId from '@framework/utils/get-checkout-id'
|
||||
import { checkoutToCart } from './utils'
|
||||
|
||||
const defaultOpts = {
|
||||
query: checkoutLineItemAddMutation,
|
||||
}
|
||||
|
||||
export type AddItemInput = UseAddItemInput<any>
|
||||
|
||||
export const fetcher: HookFetcher<Cart, any> = async (
|
||||
options,
|
||||
{ checkoutId, item },
|
||||
fetch
|
||||
) => {
|
||||
if (
|
||||
item.quantity &&
|
||||
(!Number.isInteger(item.quantity) || item.quantity! < 1)
|
||||
) {
|
||||
throw new CommerceError({
|
||||
message: 'The item quantity has to be a valid integer greater than 0',
|
||||
})
|
||||
}
|
||||
|
||||
const data = await fetch<any, any>({
|
||||
...options,
|
||||
variables: {
|
||||
checkoutId,
|
||||
lineItems: [item],
|
||||
},
|
||||
})
|
||||
|
||||
return checkoutToCart(data?.checkoutLineItemsAdd)
|
||||
}
|
||||
|
||||
export function extendHook(customFetcher: typeof fetcher) {
|
||||
const useAddItem = () => {
|
||||
const { mutate, data: cart } = useCart()
|
||||
const fn = useCartAddItem(defaultOpts, customFetcher)
|
||||
|
||||
return useCallback(
|
||||
async function addItem(input: AddItemInput) {
|
||||
const data = await fn({
|
||||
item: {
|
||||
variantId: input.variantId,
|
||||
quantity: input.quantity ?? 1,
|
||||
},
|
||||
checkoutId: getCheckoutId(cart?.id),
|
||||
})
|
||||
await mutate(data, false)
|
||||
return data
|
||||
},
|
||||
[fn, mutate]
|
||||
)
|
||||
}
|
||||
|
||||
useAddItem.extend = extendHook
|
||||
|
||||
return useAddItem
|
||||
}
|
||||
|
||||
export default extendHook(fetcher)
|
67
framework/shopify/cart/use-cart.tsx
Normal file
67
framework/shopify/cart/use-cart.tsx
Normal file
@ -0,0 +1,67 @@
|
||||
import type { HookFetcher } from '@commerce/utils/types'
|
||||
import type { SwrOptions } from '@commerce/utils/use-data'
|
||||
|
||||
import useResponse from '@commerce/utils/use-response'
|
||||
import useCommerceCart, { CartInput } from '@commerce/cart/use-cart'
|
||||
import getCheckoutQuery from '@framework/utils/queries/get-checkout-query'
|
||||
|
||||
import { Cart } from '@commerce/types'
|
||||
import { checkoutToCart, checkoutCreate } from './utils'
|
||||
|
||||
const defaultOpts = {
|
||||
query: getCheckoutQuery,
|
||||
}
|
||||
|
||||
export const fetcher: HookFetcher<Cart | null, CartInput> = async (
|
||||
options,
|
||||
{ cartId: checkoutId },
|
||||
fetch
|
||||
) => {
|
||||
let checkout
|
||||
|
||||
if (checkoutId) {
|
||||
const data = await fetch({
|
||||
...defaultOpts,
|
||||
...options,
|
||||
variables: {
|
||||
checkoutId,
|
||||
},
|
||||
})
|
||||
checkout = data?.node
|
||||
}
|
||||
|
||||
if (checkout?.completedAt || !checkoutId) {
|
||||
checkout = await checkoutCreate(fetch)
|
||||
}
|
||||
|
||||
return checkoutToCart({ checkout })
|
||||
}
|
||||
|
||||
export function extendHook(
|
||||
customFetcher: typeof fetcher,
|
||||
swrOptions?: SwrOptions<Cart | null, CartInput>
|
||||
) {
|
||||
const useCart = () => {
|
||||
const response = useCommerceCart(defaultOpts, [], customFetcher, {
|
||||
revalidateOnFocus: false,
|
||||
...swrOptions,
|
||||
})
|
||||
const res = useResponse(response, {
|
||||
descriptors: {
|
||||
isEmpty: {
|
||||
get() {
|
||||
return (response.data?.lineItems.length ?? 0) <= 0
|
||||
},
|
||||
enumerable: true,
|
||||
},
|
||||
},
|
||||
})
|
||||
return res
|
||||
}
|
||||
|
||||
useCart.extend = extendHook
|
||||
|
||||
return useCart
|
||||
}
|
||||
|
||||
export default extendHook(fetcher)
|
72
framework/shopify/cart/use-remove-item.tsx
Normal file
72
framework/shopify/cart/use-remove-item.tsx
Normal file
@ -0,0 +1,72 @@
|
||||
import { useCallback } from 'react'
|
||||
import { HookFetcher } from '@commerce/utils/types'
|
||||
import { ValidationError } from '@commerce/utils/errors'
|
||||
import useCartRemoveItem, {
|
||||
RemoveItemInput as UseRemoveItemInput,
|
||||
} from '@commerce/cart/use-remove-item'
|
||||
|
||||
import useCart from './use-cart'
|
||||
|
||||
import type { Cart, LineItem, RemoveCartItemBody } from '@commerce/types'
|
||||
import { checkoutLineItemRemoveMutation } from '@framework/utils/mutations'
|
||||
import getCheckoutId from '@framework/utils/get-checkout-id'
|
||||
import { checkoutToCart } from './utils'
|
||||
|
||||
const defaultOpts = {
|
||||
query: checkoutLineItemRemoveMutation,
|
||||
}
|
||||
|
||||
export type RemoveItemFn<T = any> = T extends LineItem
|
||||
? (input?: RemoveItemInput<T>) => Promise<Cart | null>
|
||||
: (input: RemoveItemInput<T>) => Promise<Cart | null>
|
||||
|
||||
export type RemoveItemInput<T = any> = T extends LineItem
|
||||
? Partial<UseRemoveItemInput>
|
||||
: UseRemoveItemInput
|
||||
|
||||
export const fetcher: HookFetcher<Cart | null, any> = async (
|
||||
options,
|
||||
{ itemId, checkoutId },
|
||||
fetch
|
||||
) => {
|
||||
const data = await fetch<any>({
|
||||
...defaultOpts,
|
||||
...options,
|
||||
variables: { lineItemIds: [itemId], checkoutId },
|
||||
})
|
||||
return checkoutToCart(data?.checkoutLineItemsRemove)
|
||||
}
|
||||
|
||||
export function extendHook(customFetcher: typeof fetcher) {
|
||||
const useRemoveItem = <T extends LineItem | undefined = undefined>(
|
||||
item?: T
|
||||
) => {
|
||||
const { mutate, data: cart } = useCart()
|
||||
const fn = useCartRemoveItem<Cart | null, any>(defaultOpts, customFetcher)
|
||||
const removeItem: RemoveItemFn<LineItem> = async (input) => {
|
||||
const itemId = input?.id ?? item?.id
|
||||
|
||||
if (!itemId) {
|
||||
throw new ValidationError({
|
||||
message: 'Invalid input used for this operation',
|
||||
})
|
||||
}
|
||||
|
||||
const data = await fn({
|
||||
checkoutId: getCheckoutId(cart?.id),
|
||||
itemId,
|
||||
})
|
||||
|
||||
await mutate(data, false)
|
||||
return data
|
||||
}
|
||||
|
||||
return useCallback(removeItem as RemoveItemFn<T>, [fn, mutate])
|
||||
}
|
||||
|
||||
useRemoveItem.extend = extendHook
|
||||
|
||||
return useRemoveItem
|
||||
}
|
||||
|
||||
export default extendHook(fetcher)
|
85
framework/shopify/cart/use-update-item.tsx
Normal file
85
framework/shopify/cart/use-update-item.tsx
Normal file
@ -0,0 +1,85 @@
|
||||
import { useCallback } from 'react'
|
||||
import debounce from 'lodash.debounce'
|
||||
import type { HookFetcher } from '@commerce/utils/types'
|
||||
import { ValidationError } from '@commerce/utils/errors'
|
||||
import useCartUpdateItem, {
|
||||
UpdateItemInput as UseUpdateItemInput,
|
||||
} from '@commerce/cart/use-update-item'
|
||||
|
||||
import { fetcher as removeFetcher } from './use-remove-item'
|
||||
|
||||
import useCart from './use-cart'
|
||||
|
||||
import type { Cart, LineItem, UpdateCartItemBody } from '@commerce/types'
|
||||
import { checkoutToCart } from './utils'
|
||||
import checkoutLineItemUpdateMutation from '@framework/utils/mutations/checkout-line-item-update'
|
||||
import getCheckoutId from '@framework/utils/get-checkout-id'
|
||||
|
||||
const defaultOpts = {
|
||||
query: checkoutLineItemUpdateMutation,
|
||||
}
|
||||
|
||||
export type UpdateItemInput<T = any> = T extends LineItem
|
||||
? Partial<UseUpdateItemInput<LineItem>>
|
||||
: UseUpdateItemInput<LineItem>
|
||||
|
||||
export const fetcher: HookFetcher<Cart | null, any> = async (
|
||||
options,
|
||||
{ item, checkoutId },
|
||||
fetch
|
||||
) => {
|
||||
if (Number.isInteger(item.quantity)) {
|
||||
// Also allow the update hook to remove an item if the quantity is lower than 1
|
||||
if (item.quantity! < 1) {
|
||||
return removeFetcher(null, { itemId: item.id, checkoutId }, fetch)
|
||||
}
|
||||
} else if (item.quantity) {
|
||||
throw new ValidationError({
|
||||
message: 'The item quantity has to be a valid integer',
|
||||
})
|
||||
}
|
||||
const data = await fetch<any, any>({
|
||||
...defaultOpts,
|
||||
...options,
|
||||
variables: { checkoutId, lineItems: [item] },
|
||||
})
|
||||
|
||||
return checkoutToCart(data?.checkoutLineItemsUpdate)
|
||||
}
|
||||
|
||||
function extendHook(customFetcher: typeof fetcher, cfg?: { wait?: number }) {
|
||||
const useUpdateItem = <T extends LineItem | undefined = undefined>(
|
||||
item?: T
|
||||
) => {
|
||||
const { mutate, data: cart } = useCart()
|
||||
const fn = useCartUpdateItem<Cart | null, any>(defaultOpts, customFetcher)
|
||||
|
||||
return useCallback(
|
||||
debounce(async (input: UpdateItemInput<T>) => {
|
||||
const itemId = input.id ?? item?.id
|
||||
const variantId = input.productId ?? item?.variantId
|
||||
|
||||
if (!itemId || !variantId) {
|
||||
throw new ValidationError({
|
||||
message: 'Invalid input used for this operation',
|
||||
})
|
||||
}
|
||||
|
||||
const data = await fn({
|
||||
item: { id: itemId, variantId, quantity: input.quantity },
|
||||
checkoutId: getCheckoutId(cart?.id),
|
||||
})
|
||||
|
||||
await mutate(data, false)
|
||||
return data
|
||||
}, cfg?.wait ?? 500),
|
||||
[fn, mutate]
|
||||
)
|
||||
}
|
||||
|
||||
useUpdateItem.extend = extendHook
|
||||
|
||||
return useUpdateItem
|
||||
}
|
||||
|
||||
export default extendHook(fetcher)
|
20
framework/shopify/cart/utils/checkout-create.ts
Normal file
20
framework/shopify/cart/utils/checkout-create.ts
Normal file
@ -0,0 +1,20 @@
|
||||
import { SHOPIFY_CHECKOUT_COOKIE } from '@framework'
|
||||
import checkoutCreateMutation from '@framework/utils/mutations/checkout-create'
|
||||
import Cookies from 'js-cookie'
|
||||
|
||||
export const createCheckout = async (fetch: any) => {
|
||||
const data = await fetch({
|
||||
query: checkoutCreateMutation,
|
||||
})
|
||||
|
||||
const checkout = data?.checkoutCreate?.checkout
|
||||
const checkoutId = checkout?.id
|
||||
|
||||
if (checkoutId) {
|
||||
Cookies.set(SHOPIFY_CHECKOUT_COOKIE, checkoutId)
|
||||
}
|
||||
|
||||
return checkout
|
||||
}
|
||||
|
||||
export default createCheckout
|
57
framework/shopify/cart/utils/checkout-to-cart.ts
Normal file
57
framework/shopify/cart/utils/checkout-to-cart.ts
Normal file
@ -0,0 +1,57 @@
|
||||
import { Cart } from '@commerce/types'
|
||||
import { CommerceError, ValidationError } from '@commerce/utils/errors'
|
||||
import { Checkout, CheckoutLineItemEdge, Maybe } from '@framework/schema'
|
||||
|
||||
const checkoutToCart = (checkoutResponse?: any): Maybe<Cart> => {
|
||||
if (!checkoutResponse) {
|
||||
throw new CommerceError({
|
||||
message: 'Missing checkout details from response cart Response',
|
||||
})
|
||||
}
|
||||
|
||||
const {
|
||||
checkout,
|
||||
userErrors,
|
||||
}: { checkout?: Checkout; userErrors?: any[] } = checkoutResponse
|
||||
|
||||
if (userErrors && userErrors.length) {
|
||||
throw new ValidationError({
|
||||
message: userErrors[0].message,
|
||||
})
|
||||
}
|
||||
|
||||
if (!checkout) {
|
||||
throw new ValidationError({
|
||||
message: 'Missing checkout details from response cart Response',
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
...checkout,
|
||||
currency: { code: checkout.currencyCode },
|
||||
lineItems: checkout.lineItems?.edges.map(
|
||||
({
|
||||
node: { id, title: name, quantity, variant },
|
||||
}: CheckoutLineItemEdge) => ({
|
||||
id,
|
||||
checkoutUrl: checkout.webUrl,
|
||||
variantId: variant?.id,
|
||||
productId: id,
|
||||
name,
|
||||
quantity,
|
||||
discounts: [],
|
||||
path: '',
|
||||
variant: {
|
||||
id: variant?.id,
|
||||
image: {
|
||||
url: variant?.image?.src,
|
||||
altText: variant?.title,
|
||||
},
|
||||
price: variant?.price,
|
||||
},
|
||||
})
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
export default checkoutToCart
|
2
framework/shopify/cart/utils/index.ts
Normal file
2
framework/shopify/cart/utils/index.ts
Normal file
@ -0,0 +1,2 @@
|
||||
export { default as checkoutToCart } from './checkout-to-cart'
|
||||
export { default as checkoutCreate } from './checkout-create'
|
34
framework/shopify/common/get-all-pages.ts
Normal file
34
framework/shopify/common/get-all-pages.ts
Normal file
@ -0,0 +1,34 @@
|
||||
import { getConfig, ShopifyConfig } from '../api'
|
||||
import { Page, PageEdge } from '../schema'
|
||||
import { getAllPagesQuery } from '../utils/queries'
|
||||
|
||||
type Variables = {
|
||||
first?: number
|
||||
}
|
||||
|
||||
type ReturnType = {
|
||||
pages: Page[]
|
||||
}
|
||||
|
||||
const getAllPages = async (options?: {
|
||||
variables?: Variables
|
||||
config: ShopifyConfig
|
||||
preview?: boolean
|
||||
}): Promise<ReturnType> => {
|
||||
let { config, variables = { first: 250 } } = options ?? {}
|
||||
config = getConfig(config)
|
||||
|
||||
const { data } = await config.fetch(getAllPagesQuery, { variables })
|
||||
|
||||
const pages = data.pages.edges.map(({ node }: PageEdge) => {
|
||||
return {
|
||||
...node,
|
||||
name: node.handle,
|
||||
url: `${config!.locale}/${node.handle}`,
|
||||
}
|
||||
})
|
||||
|
||||
return { pages }
|
||||
}
|
||||
|
||||
export default getAllPages
|
27
framework/shopify/common/get-page.ts
Normal file
27
framework/shopify/common/get-page.ts
Normal file
@ -0,0 +1,27 @@
|
||||
import { ShopifyConfig, getConfig } from '../api'
|
||||
import type { Page } from '../types'
|
||||
|
||||
export type { Page }
|
||||
|
||||
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
|
31
framework/shopify/common/get-site-info.ts
Normal file
31
framework/shopify/common/get-site-info.ts
Normal file
@ -0,0 +1,31 @@
|
||||
import { CollectionEdge } from '@framework/schema'
|
||||
import { getConfig, ShopifyConfig } from '../api'
|
||||
import getAllCollectionsQuery from '../utils/queries/get-all-collections-query'
|
||||
|
||||
const getSiteInfo = async (options?: {
|
||||
variables?: any
|
||||
config: ShopifyConfig
|
||||
preview?: boolean
|
||||
}) => {
|
||||
let { config, variables = { first: 250 } } = options ?? {}
|
||||
|
||||
config = getConfig(config)
|
||||
|
||||
const { data } = await config.fetch(getAllCollectionsQuery, { variables })
|
||||
const edges = data.collections?.edges ?? []
|
||||
|
||||
const categories = edges.map(
|
||||
({ node: { id: entityId, title: name, handle } }: CollectionEdge) => ({
|
||||
entityId,
|
||||
name,
|
||||
path: `/${handle}`,
|
||||
})
|
||||
)
|
||||
|
||||
return {
|
||||
categories,
|
||||
brands: [],
|
||||
}
|
||||
}
|
||||
|
||||
export default getSiteInfo
|
32
framework/shopify/customer/use-customer.tsx
Normal file
32
framework/shopify/customer/use-customer.tsx
Normal file
@ -0,0 +1,32 @@
|
||||
import type { HookFetcher } from '@commerce/utils/types'
|
||||
import type { SwrOptions } from '@commerce/utils/use-data'
|
||||
import useCommerceCustomer from '@commerce/use-customer'
|
||||
|
||||
const defaultOpts = {}
|
||||
|
||||
export type Customer = {
|
||||
entityId: number
|
||||
firstName: string
|
||||
lastName: string
|
||||
email: string
|
||||
}
|
||||
export type CustomerData = {}
|
||||
|
||||
export const fetcher: HookFetcher<Customer | null> = async () => {
|
||||
return null
|
||||
}
|
||||
|
||||
export function extendHook(
|
||||
customFetcher: typeof fetcher,
|
||||
swrOptions?: SwrOptions<Customer | null>
|
||||
) {
|
||||
const useCustomer = () => {
|
||||
return { data: { firstName: null, lastName: null, email: null } }
|
||||
}
|
||||
|
||||
useCustomer.extend = extendHook
|
||||
|
||||
return useCustomer
|
||||
}
|
||||
|
||||
export default extendHook(fetcher)
|
78
framework/shopify/index.tsx
Normal file
78
framework/shopify/index.tsx
Normal file
@ -0,0 +1,78 @@
|
||||
import { ReactNode } from 'react'
|
||||
import * as React from 'react'
|
||||
|
||||
import {
|
||||
CommerceConfig,
|
||||
CommerceProvider as CoreCommerceProvider,
|
||||
useCommerce as useCoreCommerce,
|
||||
} from '@commerce'
|
||||
|
||||
import { CommerceError, FetcherError } from '@commerce/utils/errors'
|
||||
|
||||
export const SHOPIFY_CHECKOUT_COOKIE = 'shopify_checkoutId'
|
||||
|
||||
async function getText(res: Response) {
|
||||
try {
|
||||
return (await res.text()) || res.statusText
|
||||
} catch (error) {
|
||||
return res.statusText
|
||||
}
|
||||
}
|
||||
|
||||
async function getError(res: Response) {
|
||||
if (res.headers.get('Content-Type')?.includes('application/json')) {
|
||||
const data = await res.json()
|
||||
|
||||
return new FetcherError({ errors: data.errors, status: res.status })
|
||||
}
|
||||
return new FetcherError({ message: await getText(res), status: res.status })
|
||||
}
|
||||
|
||||
export const shopifyConfig: CommerceConfig = {
|
||||
locale: 'en-us',
|
||||
cartCookie: SHOPIFY_CHECKOUT_COOKIE,
|
||||
async fetcher({ method = 'POST', variables, query }) {
|
||||
const res = await fetch(
|
||||
`https://${process.env.NEXT_PUBLIC_SHOPIFY_STORE_DOMAIN}/api/2021-01/graphql.json`,
|
||||
{
|
||||
method,
|
||||
body: JSON.stringify({ query, variables }),
|
||||
headers: {
|
||||
'X-Shopify-Storefront-Access-Token':
|
||||
process.env.NEXT_PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
if (res.ok) {
|
||||
const { data, errors } = await res.json()
|
||||
|
||||
if (errors && errors.length) {
|
||||
throw new CommerceError({
|
||||
message: errors[0].message,
|
||||
})
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
throw await getError(res)
|
||||
},
|
||||
}
|
||||
|
||||
export type ShopifyConfig = Partial<CommerceConfig>
|
||||
|
||||
export type ShopifyProps = {
|
||||
children?: ReactNode
|
||||
locale: string
|
||||
} & ShopifyConfig
|
||||
|
||||
export function CommerceProvider({ children, ...config }: ShopifyProps) {
|
||||
return (
|
||||
<CoreCommerceProvider config={{ ...shopifyConfig, ...config }}>
|
||||
{children}
|
||||
</CoreCommerceProvider>
|
||||
)
|
||||
}
|
||||
|
||||
export const useCommerce = () => useCoreCommerce()
|
29
framework/shopify/product/get-all-collections.ts
Normal file
29
framework/shopify/product/get-all-collections.ts
Normal file
@ -0,0 +1,29 @@
|
||||
import { CollectionEdge } from '@framework/schema'
|
||||
import { getConfig, ShopifyConfig } from '../api'
|
||||
import getAllCollectionsQuery from '../utils/queries/get-all-collections-query'
|
||||
|
||||
const getAllCollections = async (options?: {
|
||||
variables?: any
|
||||
config: ShopifyConfig
|
||||
preview?: boolean
|
||||
}) => {
|
||||
let { config, variables = { first: 250 } } = options ?? {}
|
||||
config = getConfig(config)
|
||||
|
||||
const { data } = await config.fetch(getAllCollectionsQuery, { variables })
|
||||
const edges = data.collections?.edges ?? []
|
||||
|
||||
const categories = edges.map(
|
||||
({ node: { id: entityId, title: name, handle } }: CollectionEdge) => ({
|
||||
entityId,
|
||||
name,
|
||||
path: `/${handle}`,
|
||||
})
|
||||
)
|
||||
|
||||
return {
|
||||
categories,
|
||||
}
|
||||
}
|
||||
|
||||
export default getAllCollections
|
34
framework/shopify/product/get-all-product-paths.ts
Normal file
34
framework/shopify/product/get-all-product-paths.ts
Normal file
@ -0,0 +1,34 @@
|
||||
import { getConfig, ShopifyConfig } from '../api'
|
||||
import { ProductEdge } from '../schema'
|
||||
import getAllProductsPathsQuery from '../utils/queries/get-all-products-paths-query'
|
||||
|
||||
type ReturnType = {
|
||||
products: any[]
|
||||
}
|
||||
|
||||
const getAllProductPaths = async (options?: {
|
||||
variables?: any
|
||||
config?: ShopifyConfig
|
||||
previe?: boolean
|
||||
}): Promise<ReturnType> => {
|
||||
let { config, variables = { first: 250 } } = options ?? {}
|
||||
config = getConfig(config)
|
||||
|
||||
const { data } = await config.fetch(getAllProductsPathsQuery, {
|
||||
variables,
|
||||
})
|
||||
|
||||
const edges = data.products?.edges
|
||||
const productInfo = data.products?.productInfo
|
||||
const hasNextPage = productInfo?.hasNextPage
|
||||
|
||||
return {
|
||||
products: edges.map(({ node: { handle } }: ProductEdge) => ({
|
||||
node: {
|
||||
path: `/${handle}`,
|
||||
},
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
export default getAllProductPaths
|
39
framework/shopify/product/get-all-products.ts
Normal file
39
framework/shopify/product/get-all-products.ts
Normal file
@ -0,0 +1,39 @@
|
||||
import { GraphQLFetcherResult } from '@commerce/api'
|
||||
import toCommerceProducts from '../utils/to-commerce-products'
|
||||
import { getConfig, ShopifyConfig } from '../api'
|
||||
import { Product } from '../schema'
|
||||
import { getAllProductsQuery } from '../utils/queries'
|
||||
|
||||
export type ProductNode = Product
|
||||
|
||||
type Variables = {
|
||||
first?: number
|
||||
field?: string
|
||||
}
|
||||
|
||||
type ReturnType = {
|
||||
products: any[]
|
||||
}
|
||||
|
||||
const getAllProducts = async (options: {
|
||||
variables?: Variables
|
||||
config?: ShopifyConfig
|
||||
preview?: boolean
|
||||
}): Promise<ReturnType> => {
|
||||
let { config, variables = { first: 250 } } = options ?? {}
|
||||
config = getConfig(config)
|
||||
|
||||
const { data }: GraphQLFetcherResult = await config.fetch(
|
||||
getAllProductsQuery,
|
||||
{ variables }
|
||||
)
|
||||
|
||||
const shopifyProducts = data.products?.edges
|
||||
const products = toCommerceProducts(shopifyProducts)
|
||||
|
||||
return {
|
||||
products,
|
||||
}
|
||||
}
|
||||
|
||||
export default getAllProducts
|
37
framework/shopify/product/get-product.ts
Normal file
37
framework/shopify/product/get-product.ts
Normal file
@ -0,0 +1,37 @@
|
||||
import { GraphQLFetcherResult } from '@commerce/api'
|
||||
|
||||
import { getConfig, ShopifyConfig } from '../api'
|
||||
import { Product } from '../schema'
|
||||
import { toCommerceProduct } from '../utils/to-commerce-products'
|
||||
import getProductQuery from '../utils/queries/get-product-query'
|
||||
|
||||
export type ProductNode = Product
|
||||
|
||||
type Variables = {
|
||||
slug: string
|
||||
}
|
||||
|
||||
type Options = {
|
||||
variables: Variables
|
||||
config: ShopifyConfig
|
||||
preview?: boolean
|
||||
}
|
||||
|
||||
type ReturnType = {
|
||||
product: any
|
||||
}
|
||||
|
||||
const getProduct = async (options: Options): Promise<ReturnType> => {
|
||||
let { config, variables = { first: 250 } } = options ?? {}
|
||||
config = getConfig(config)
|
||||
|
||||
const {
|
||||
data: { productByHandle: product },
|
||||
}: GraphQLFetcherResult = await config.fetch(getProductQuery, { variables })
|
||||
|
||||
return {
|
||||
product: product ? toCommerceProduct(product) : null,
|
||||
}
|
||||
}
|
||||
|
||||
export default getProduct
|
2
framework/shopify/product/use-price.tsx
Normal file
2
framework/shopify/product/use-price.tsx
Normal file
@ -0,0 +1,2 @@
|
||||
export * from '@commerce/use-price'
|
||||
export { default } from '@commerce/use-price'
|
86
framework/shopify/product/use-search.tsx
Normal file
86
framework/shopify/product/use-search.tsx
Normal file
@ -0,0 +1,86 @@
|
||||
import useCommerceSearch from '@commerce/products/use-search'
|
||||
|
||||
import toCommerceProducts from '@framework/utils/to-commerce-products'
|
||||
import getAllProductsQuery from '@framework/utils/queries/get-all-products-query'
|
||||
|
||||
import type { Product } from 'framework/bigcommerce/schema'
|
||||
import type { HookFetcher } from '@commerce/utils/types'
|
||||
import type { SwrOptions } from '@commerce/utils/use-data'
|
||||
import type { ProductEdge } from '@framework/schema'
|
||||
|
||||
import {
|
||||
searchByProductType,
|
||||
searchByTag,
|
||||
} from '@framework/utils/get-search-variables'
|
||||
|
||||
import sortBy from '@framework/utils/get-sort-variables'
|
||||
|
||||
export type CommerceProductEdge = {
|
||||
node: Product
|
||||
}
|
||||
|
||||
export type SearchProductsInput = {
|
||||
search?: string
|
||||
categoryPath?: string
|
||||
sort?: string
|
||||
}
|
||||
|
||||
export type SearchRequestProductsData = {
|
||||
products?: ProductEdge[]
|
||||
}
|
||||
|
||||
export type SearchProductsData = {
|
||||
products: Product[]
|
||||
found: boolean
|
||||
}
|
||||
|
||||
export const fetcher: HookFetcher<
|
||||
SearchRequestProductsData,
|
||||
SearchProductsInput
|
||||
> = (options, { search, categoryPath, sort }, fetch) => {
|
||||
return fetch({
|
||||
query: options?.query,
|
||||
method: options?.method,
|
||||
variables: {
|
||||
...searchByProductType(search),
|
||||
...searchByTag(categoryPath),
|
||||
...sortBy(sort),
|
||||
},
|
||||
}).then(
|
||||
({ products }): SearchProductsData => {
|
||||
return {
|
||||
products: toCommerceProducts(products.edges),
|
||||
found: !!products.edges.length,
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
export function extendHook(
|
||||
customFetcher: typeof fetcher,
|
||||
swrOptions?: SwrOptions<SearchProductsData, SearchProductsInput>
|
||||
) {
|
||||
const useSearch = (input: SearchProductsInput = {}) => {
|
||||
const response = useCommerceSearch(
|
||||
{
|
||||
query: getAllProductsQuery,
|
||||
method: 'POST',
|
||||
},
|
||||
[
|
||||
['search', input.search],
|
||||
['categoryPath', input.categoryPath],
|
||||
['sort', input.sort],
|
||||
],
|
||||
customFetcher,
|
||||
{ revalidateOnFocus: false, ...swrOptions }
|
||||
)
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
useSearch.extend = extendHook
|
||||
|
||||
return useSearch
|
||||
}
|
||||
|
||||
export default extendHook(fetcher)
|
4985
framework/shopify/schema.d.ts
vendored
Normal file
4985
framework/shopify/schema.d.ts
vendored
Normal file
File diff suppressed because it is too large
Load Diff
9631
framework/shopify/schema.graphql
Normal file
9631
framework/shopify/schema.graphql
Normal file
File diff suppressed because it is too large
Load Diff
38
framework/shopify/utils/fetch-graphql-api.ts
Normal file
38
framework/shopify/utils/fetch-graphql-api.ts
Normal file
@ -0,0 +1,38 @@
|
||||
import type { GraphQLFetcher } from '@commerce/api'
|
||||
import { FetcherError } from '@commerce/utils/errors'
|
||||
import { getConfig } from '../api/index'
|
||||
import fetch from './fetch'
|
||||
|
||||
const fetchGraphqlApi: GraphQLFetcher = async (
|
||||
query: string,
|
||||
{ variables } = {},
|
||||
fetchOptions
|
||||
) => {
|
||||
const { commerceUrl, apiToken } = getConfig()
|
||||
|
||||
const res = await fetch(`https://${commerceUrl}/api/2021-01/graphql.json`, {
|
||||
...fetchOptions,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-Shopify-Storefront-Access-Token': apiToken,
|
||||
...fetchOptions?.headers,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query,
|
||||
variables,
|
||||
}),
|
||||
})
|
||||
|
||||
const json = await res.json()
|
||||
|
||||
if (json.errors) {
|
||||
throw new FetcherError({
|
||||
errors: json.errors ?? [{ message: 'Failed to fetch Shopify API' }],
|
||||
status: res.status,
|
||||
})
|
||||
}
|
||||
|
||||
return { data: json.data, res }
|
||||
}
|
||||
export default fetchGraphqlApi
|
3
framework/shopify/utils/fetch.ts
Normal file
3
framework/shopify/utils/fetch.ts
Normal file
@ -0,0 +1,3 @@
|
||||
import zeitFetch from '@vercel/fetch'
|
||||
|
||||
export default zeitFetch()
|
8
framework/shopify/utils/get-checkout-id.ts
Normal file
8
framework/shopify/utils/get-checkout-id.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import Cookies from 'js-cookie'
|
||||
import { SHOPIFY_CHECKOUT_COOKIE } from '..'
|
||||
|
||||
const getCheckoutId = (id?: string) => {
|
||||
return id ?? Cookies.get(SHOPIFY_CHECKOUT_COOKIE)
|
||||
}
|
||||
|
||||
export default getCheckoutId
|
15
framework/shopify/utils/get-search-variables.ts
Normal file
15
framework/shopify/utils/get-search-variables.ts
Normal file
@ -0,0 +1,15 @@
|
||||
export const searchByProductType = (search?: string) => {
|
||||
return search
|
||||
? {
|
||||
query: `product_type:${search}`,
|
||||
}
|
||||
: {}
|
||||
}
|
||||
|
||||
export const searchByTag = (categoryPath?: string) => {
|
||||
return categoryPath
|
||||
? {
|
||||
query: `tag:${categoryPath}`,
|
||||
}
|
||||
: {}
|
||||
}
|
32
framework/shopify/utils/get-sort-variables.ts
Normal file
32
framework/shopify/utils/get-sort-variables.ts
Normal file
@ -0,0 +1,32 @@
|
||||
const getSortVariables = (sort?: string) => {
|
||||
let output = {}
|
||||
switch (sort) {
|
||||
case 'price-asc':
|
||||
output = {
|
||||
sortKey: 'PRICE',
|
||||
reverse: false,
|
||||
}
|
||||
break
|
||||
case 'price-desc':
|
||||
output = {
|
||||
sortKey: 'PRICE',
|
||||
reverse: true,
|
||||
}
|
||||
break
|
||||
case 'trending-desc':
|
||||
output = {
|
||||
sortKey: 'BEST_SELLING',
|
||||
reverse: false,
|
||||
}
|
||||
break
|
||||
case 'latest-desc':
|
||||
output = {
|
||||
sortKey: 'CREATED_AT',
|
||||
reverse: true,
|
||||
}
|
||||
break
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
export default getSortVariables
|
15
framework/shopify/utils/mutations/checkout-create.ts
Normal file
15
framework/shopify/utils/mutations/checkout-create.ts
Normal file
@ -0,0 +1,15 @@
|
||||
const checkoutCreateMutation = /* GraphQL */ `
|
||||
mutation {
|
||||
checkoutCreate(input: {}) {
|
||||
userErrors {
|
||||
message
|
||||
field
|
||||
}
|
||||
checkout {
|
||||
id
|
||||
webUrl
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
export default checkoutCreateMutation
|
16
framework/shopify/utils/mutations/checkout-line-item-add.ts
Normal file
16
framework/shopify/utils/mutations/checkout-line-item-add.ts
Normal file
@ -0,0 +1,16 @@
|
||||
import { checkoutDetailsFragment } from '../queries/get-checkout-query'
|
||||
|
||||
const checkoutLineItemAddMutation = /* GraphQL */ `
|
||||
mutation($checkoutId: ID!, $lineItems: [CheckoutLineItemInput!]!) {
|
||||
checkoutLineItemsAdd(checkoutId: $checkoutId, lineItems: $lineItems) {
|
||||
userErrors {
|
||||
message
|
||||
field
|
||||
}
|
||||
checkout {
|
||||
${checkoutDetailsFragment}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
export default checkoutLineItemAddMutation
|
@ -0,0 +1,19 @@
|
||||
import { checkoutDetailsFragment } from '../queries/get-checkout-query'
|
||||
|
||||
const checkoutLineItemRemoveMutation = /* GraphQL */ `
|
||||
mutation($checkoutId: ID!, $lineItemIds: [ID!]!) {
|
||||
checkoutLineItemsRemove(
|
||||
checkoutId: $checkoutId
|
||||
lineItemIds: $lineItemIds
|
||||
) {
|
||||
userErrors {
|
||||
message
|
||||
field
|
||||
}
|
||||
checkout {
|
||||
${checkoutDetailsFragment}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
export default checkoutLineItemRemoveMutation
|
@ -0,0 +1,16 @@
|
||||
import { checkoutDetailsFragment } from '../queries/get-checkout-query'
|
||||
|
||||
const checkoutLineItemUpdateMutation = /* GraphQL */ `
|
||||
mutation($checkoutId: ID!, $lineItems: [CheckoutLineItemUpdateInput!]!) {
|
||||
checkoutLineItemsUpdate(checkoutId: $checkoutId, lineItems: $lineItems) {
|
||||
userErrors {
|
||||
message
|
||||
field
|
||||
}
|
||||
checkout {
|
||||
${checkoutDetailsFragment}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
export default checkoutLineItemUpdateMutation
|
4
framework/shopify/utils/mutations/index.ts
Normal file
4
framework/shopify/utils/mutations/index.ts
Normal file
@ -0,0 +1,4 @@
|
||||
export { default as checkoutCreateMutation } from './checkout-create'
|
||||
export { default as checkoutLineItemAddMutation } from './checkout-line-item-add'
|
||||
export { default as checkoutLineItemUpdateMutation } from './checkout-create'
|
||||
export { default as checkoutLineItemRemoveMutation } from './checkout-line-item-remove'
|
14
framework/shopify/utils/queries/get-all-collections-query.ts
Normal file
14
framework/shopify/utils/queries/get-all-collections-query.ts
Normal file
@ -0,0 +1,14 @@
|
||||
const getSiteCollectionsQuery = /* GraphQL */ `
|
||||
query getSiteCollections($first: Int!) {
|
||||
collections(first: $first) {
|
||||
edges {
|
||||
node {
|
||||
id
|
||||
title
|
||||
handle
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
export default getSiteCollectionsQuery
|
17
framework/shopify/utils/queries/get-all-pages-query.ts
Normal file
17
framework/shopify/utils/queries/get-all-pages-query.ts
Normal file
@ -0,0 +1,17 @@
|
||||
export const getAllPagesQuery = /* GraphQL */ `
|
||||
query($first: Int!) {
|
||||
pages(first: $first) {
|
||||
edges {
|
||||
node {
|
||||
id
|
||||
title
|
||||
handle
|
||||
body
|
||||
bodySummary
|
||||
url
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
export default getAllPagesQuery
|
@ -0,0 +1,16 @@
|
||||
const getAllProductsPathsQuery = /* GraphQL */ `
|
||||
query getAllProductPaths($first: Int!) {
|
||||
products(first: $first) {
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
hasPreviousPage
|
||||
}
|
||||
edges {
|
||||
node {
|
||||
handle
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
export default getAllProductsPathsQuery
|
47
framework/shopify/utils/queries/get-all-products-query.ts
Normal file
47
framework/shopify/utils/queries/get-all-products-query.ts
Normal file
@ -0,0 +1,47 @@
|
||||
const getAllProductsQuery = /* GraphQL */ `
|
||||
query getAllProducts(
|
||||
$first: Int = 250
|
||||
$query: String = ""
|
||||
$sortKey: ProductSortKeys = RELEVANCE
|
||||
$reverse: Boolean = false
|
||||
) {
|
||||
products(
|
||||
first: $first
|
||||
sortKey: $sortKey
|
||||
reverse: $reverse
|
||||
query: $query
|
||||
) {
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
hasPreviousPage
|
||||
}
|
||||
edges {
|
||||
node {
|
||||
id
|
||||
title
|
||||
vendor
|
||||
handle
|
||||
description
|
||||
priceRange {
|
||||
minVariantPrice {
|
||||
amount
|
||||
currencyCode
|
||||
}
|
||||
}
|
||||
images(first: 1) {
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
hasPreviousPage
|
||||
}
|
||||
edges {
|
||||
node {
|
||||
src
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
export default getAllProductsQuery
|
40
framework/shopify/utils/queries/get-checkout-query.ts
Normal file
40
framework/shopify/utils/queries/get-checkout-query.ts
Normal file
@ -0,0 +1,40 @@
|
||||
export const checkoutDetailsFragment = /* GraphQL */ `
|
||||
id
|
||||
webUrl
|
||||
subtotalPrice
|
||||
totalTax
|
||||
totalPrice
|
||||
currencyCode
|
||||
lineItems(first: 250) {
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
hasPreviousPage
|
||||
}
|
||||
edges {
|
||||
node {
|
||||
id
|
||||
title
|
||||
variant {
|
||||
id
|
||||
title
|
||||
image {
|
||||
src
|
||||
}
|
||||
price
|
||||
}
|
||||
quantity
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
const getCheckoutQuery = /* GraphQL */ `
|
||||
query($checkoutId: ID!) {
|
||||
node(id: $checkoutId) {
|
||||
... on Checkout {
|
||||
${checkoutDetailsFragment}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
export default getCheckoutQuery
|
59
framework/shopify/utils/queries/get-product-query.ts
Normal file
59
framework/shopify/utils/queries/get-product-query.ts
Normal file
@ -0,0 +1,59 @@
|
||||
const getProductQuery = /* GraphQL */ `
|
||||
query getProductBySlug($slug: String!) {
|
||||
productByHandle(handle: $slug) {
|
||||
id
|
||||
handle
|
||||
title
|
||||
productType
|
||||
vendor
|
||||
description
|
||||
descriptionHtml
|
||||
options {
|
||||
id
|
||||
name
|
||||
values
|
||||
}
|
||||
priceRange {
|
||||
maxVariantPrice {
|
||||
amount
|
||||
currencyCode
|
||||
}
|
||||
minVariantPrice {
|
||||
amount
|
||||
currencyCode
|
||||
}
|
||||
}
|
||||
variants(first: 250) {
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
hasPreviousPage
|
||||
}
|
||||
edges {
|
||||
node {
|
||||
id
|
||||
title
|
||||
selectedOptions {
|
||||
name
|
||||
value
|
||||
}
|
||||
price
|
||||
compareAtPrice
|
||||
}
|
||||
}
|
||||
}
|
||||
images(first: 250) {
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
hasPreviousPage
|
||||
}
|
||||
edges {
|
||||
node {
|
||||
src
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export default getProductQuery
|
6
framework/shopify/utils/queries/index.ts
Normal file
6
framework/shopify/utils/queries/index.ts
Normal file
@ -0,0 +1,6 @@
|
||||
export { default as getSiteCollectionsQuery } from './get-all-collections-query'
|
||||
export { default as getProductQuery } from './get-all-products-paths-query'
|
||||
export { default as getAllProductsQuery } from './get-all-products-query'
|
||||
export { default as getAllProductsPathtsQuery } from './get-all-products-paths-query'
|
||||
export { default as getCheckoutQuery } from './get-checkout-query'
|
||||
export { default as getAllPagesQuery } from './get-all-pages-query'
|
96
framework/shopify/utils/to-commerce-products.ts
Normal file
96
framework/shopify/utils/to-commerce-products.ts
Normal file
@ -0,0 +1,96 @@
|
||||
import {
|
||||
Product as ShopifyProduct,
|
||||
ImageEdge,
|
||||
SelectedOption,
|
||||
ProductEdge,
|
||||
ProductVariantEdge,
|
||||
MoneyV2,
|
||||
ProductOption,
|
||||
} from '../schema'
|
||||
|
||||
const money = ({ amount, currencyCode }: MoneyV2) => {
|
||||
return {
|
||||
value: +amount,
|
||||
currencyCode,
|
||||
}
|
||||
}
|
||||
|
||||
const tranformProductOption = ({
|
||||
id,
|
||||
name: displayName,
|
||||
values,
|
||||
}: ProductOption) => ({
|
||||
__typename: 'MultipleChoiceOption',
|
||||
displayName,
|
||||
values: values.map((value) => ({
|
||||
label: value,
|
||||
})),
|
||||
})
|
||||
|
||||
const transformImages = (images: ImageEdge[]) =>
|
||||
images.map(({ node: { src: url } }) => ({
|
||||
url,
|
||||
}))
|
||||
|
||||
export const toCommerceProduct = (product: ShopifyProduct) => {
|
||||
const {
|
||||
id,
|
||||
title: name,
|
||||
vendor,
|
||||
images: { edges: images },
|
||||
variants: { edges: variants },
|
||||
description,
|
||||
handle: slug,
|
||||
priceRange,
|
||||
options,
|
||||
} = product
|
||||
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
slug,
|
||||
vendor,
|
||||
description,
|
||||
path: `/${slug}`,
|
||||
price: money(priceRange.minVariantPrice),
|
||||
images: transformImages(images),
|
||||
variants: variants.map(
|
||||
({ node: { id, selectedOptions } }: ProductVariantEdge) => {
|
||||
return {
|
||||
id,
|
||||
options: selectedOptions.map(({ name, value }: SelectedOption) =>
|
||||
tranformProductOption({
|
||||
id,
|
||||
name,
|
||||
values: [value],
|
||||
} as ProductOption)
|
||||
),
|
||||
}
|
||||
}
|
||||
),
|
||||
options: options.map((option: ProductOption) =>
|
||||
tranformProductOption(option)
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
export default function toCommerceProducts(products: ProductEdge[]) {
|
||||
return products.map(
|
||||
({
|
||||
node: {
|
||||
id,
|
||||
title: name,
|
||||
images: { edges: images },
|
||||
handle: slug,
|
||||
priceRange,
|
||||
},
|
||||
}: ProductEdge) => ({
|
||||
id,
|
||||
name,
|
||||
images: transformImages(images),
|
||||
price: money(priceRange.minVariantPrice),
|
||||
slug,
|
||||
path: `/${slug}`,
|
||||
})
|
||||
)
|
||||
}
|
13
framework/shopify/wishlist/use-add-item.tsx
Normal file
13
framework/shopify/wishlist/use-add-item.tsx
Normal file
@ -0,0 +1,13 @@
|
||||
import { useCallback } from 'react'
|
||||
|
||||
export function emptyHook() {
|
||||
const useEmptyHook = async (options = {}) => {
|
||||
return useCallback(async function () {
|
||||
return Promise.resolve()
|
||||
}, [])
|
||||
}
|
||||
|
||||
return useEmptyHook
|
||||
}
|
||||
|
||||
export default emptyHook
|
17
framework/shopify/wishlist/use-remove-item.tsx
Normal file
17
framework/shopify/wishlist/use-remove-item.tsx
Normal file
@ -0,0 +1,17 @@
|
||||
import { useCallback } from 'react'
|
||||
|
||||
type Options = {
|
||||
includeProducts?: boolean
|
||||
}
|
||||
|
||||
export function emptyHook(options?: Options) {
|
||||
const useEmptyHook = async ({ id }: { id: string | number }) => {
|
||||
return useCallback(async function () {
|
||||
return Promise.resolve()
|
||||
}, [])
|
||||
}
|
||||
|
||||
return useEmptyHook
|
||||
}
|
||||
|
||||
export default emptyHook
|
45
framework/shopify/wishlist/use-wishlist.tsx
Normal file
45
framework/shopify/wishlist/use-wishlist.tsx
Normal file
@ -0,0 +1,45 @@
|
||||
import { HookFetcher } from '@commerce/utils/types'
|
||||
import { SwrOptions } from '@commerce/utils/use-data'
|
||||
import useCommerceWishlist from '@commerce/wishlist/use-wishlist'
|
||||
import { Product } from '../schema'
|
||||
import useCustomer from '../customer/use-customer'
|
||||
|
||||
const defaultOpts = {}
|
||||
|
||||
export type Wishlist = {
|
||||
items: [
|
||||
{
|
||||
product_id: number
|
||||
variant_id: number
|
||||
id: number
|
||||
product: Product
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
export interface UseWishlistOptions {
|
||||
includeProducts?: boolean
|
||||
}
|
||||
|
||||
export interface UseWishlistInput extends UseWishlistOptions {
|
||||
customerId?: number
|
||||
}
|
||||
|
||||
export const fetcher: HookFetcher<Wishlist | null, UseWishlistInput> = () => {
|
||||
return null
|
||||
}
|
||||
|
||||
export function extendHook(
|
||||
customFetcher: typeof fetcher,
|
||||
swrOptions?: SwrOptions<Wishlist | null, UseWishlistInput>
|
||||
) {
|
||||
const useWishlist = ({ includeProducts }: UseWishlistOptions = {}) => {
|
||||
return { data: null }
|
||||
}
|
||||
|
||||
useWishlist.extend = extendHook
|
||||
|
||||
return useWishlist
|
||||
}
|
||||
|
||||
export default extendHook(fetcher)
|
@ -1,6 +1,6 @@
|
||||
module.exports = {
|
||||
images: {
|
||||
domains: ['cdn11.bigcommerce.com'],
|
||||
domains: ['cdn11.bigcommerce.com', 'cdn.shopify.com'],
|
||||
},
|
||||
i18n: {
|
||||
locales: ['en-US', 'es'],
|
||||
|
@ -71,6 +71,7 @@ export default function Search({
|
||||
const { data } = useSearch({
|
||||
search: typeof q === 'string' ? q : '',
|
||||
categoryId: activeCategory?.entityId,
|
||||
categoryPath: activeCategory?.path,
|
||||
brandId: activeBrand?.entityId,
|
||||
sort: typeof sort === 'string' ? sort : '',
|
||||
})
|
||||
|
@ -22,8 +22,8 @@
|
||||
"@utils/*": ["utils/*"],
|
||||
"@commerce/*": ["framework/commerce/*"],
|
||||
"@commerce": ["framework/commerce"],
|
||||
"@framework/*": ["framework/bigcommerce/*"],
|
||||
"@framework": ["framework/bigcommerce"]
|
||||
"@framework/*": ["framework/shopify/*"],
|
||||
"@framework": ["framework/shopify"]
|
||||
}
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "**/*.js"],
|
||||
|
Loading…
x
Reference in New Issue
Block a user