mirror of
https://github.com/vercel/commerce.git
synced 2025-05-18 15:36:58 +00:00
Add Reaction Commerce provider
Signed-off-by: Loan Laux <loan@outgrow.io>
This commit is contained in:
parent
9b71bd77fc
commit
09249045eb
17
codegen.json
17
codegen.json
@ -1,23 +1,14 @@
|
||||
{
|
||||
"schema": {
|
||||
"https://buybutton.store/graphql": {
|
||||
"headers": {
|
||||
"Authorization": "Bearer xzy"
|
||||
}
|
||||
"http://localhost:3000/graphql": {
|
||||
"headers": {}
|
||||
}
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"./framework/bigcommerce/api/**/*.ts": {
|
||||
"noRequire": true
|
||||
}
|
||||
}
|
||||
],
|
||||
"generates": {
|
||||
"./framework/bigcommerce/schema.d.ts": {
|
||||
"./framework/reactioncommerce/schema.d.ts": {
|
||||
"plugins": ["typescript", "typescript-operations"]
|
||||
},
|
||||
"./framework/bigcommerce/schema.graphql": {
|
||||
"./framework/reactioncommerce/schema.graphql": {
|
||||
"plugins": ["schema-ast"]
|
||||
}
|
||||
},
|
||||
|
@ -1,7 +1,7 @@
|
||||
{
|
||||
"provider": "bigcommerce",
|
||||
"provider": "reactioncommerce",
|
||||
"features": {
|
||||
"wishlist": true,
|
||||
"customCheckout": false
|
||||
"wishlist": false,
|
||||
"customCheckout": true
|
||||
}
|
||||
}
|
||||
|
@ -39,6 +39,7 @@ const CartItem = ({
|
||||
const [removing, setRemoving] = useState(false)
|
||||
|
||||
const updateQuantity = async (val: number) => {
|
||||
console.log('updateQuantity', val)
|
||||
await updateItem({ quantity: val })
|
||||
}
|
||||
|
||||
|
@ -34,7 +34,7 @@ const ProductCard: FC<Props> = ({
|
||||
{product?.images && (
|
||||
<Image
|
||||
quality="85"
|
||||
src={product.images[0].url || placeholderImg}
|
||||
src={product.images[0]?.url || placeholderImg}
|
||||
alt={product.name || 'Product Image'}
|
||||
height={320}
|
||||
width={320}
|
||||
@ -70,7 +70,7 @@ const ProductCard: FC<Props> = ({
|
||||
<Image
|
||||
alt={product.name || 'Product Image'}
|
||||
className={s.productImage}
|
||||
src={product.images[0].url || placeholderImg}
|
||||
src={product.images[0]?.url || placeholderImg}
|
||||
height={540}
|
||||
width={540}
|
||||
quality="85"
|
||||
|
@ -30,7 +30,6 @@ const ProductView: FC<Props> = ({ product }) => {
|
||||
const { openSidebar } = useUI()
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [choices, setChoices] = useState<SelectedOptions>({
|
||||
size: null,
|
||||
color: null,
|
||||
})
|
||||
|
||||
@ -40,9 +39,17 @@ const ProductView: FC<Props> = ({ product }) => {
|
||||
const addToCart = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const selectedVariant = variant ? variant : product.variants[0]
|
||||
|
||||
console.log('selected variant', selectedVariant)
|
||||
|
||||
await addItem({
|
||||
productId: String(product.id),
|
||||
variantId: String(variant ? variant.id : product.variants[0].id),
|
||||
variantId: String(selectedVariant.id),
|
||||
pricing: {
|
||||
amount: selectedVariant.price,
|
||||
currencyCode: product.price.currencyCode,
|
||||
},
|
||||
})
|
||||
openSidebar()
|
||||
setLoading(false)
|
||||
|
@ -5,6 +5,7 @@ export interface CommerceAPIConfig {
|
||||
commerceUrl: string
|
||||
apiToken: string
|
||||
cartCookie: string
|
||||
cartIdCookie: string
|
||||
cartCookieMaxAge: number
|
||||
customerCookie: string
|
||||
fetch<Data = any, Variables = any>(
|
||||
|
@ -4,7 +4,7 @@
|
||||
|
||||
const merge = require('deepmerge')
|
||||
|
||||
const PROVIDERS = ['bigcommerce', 'shopify']
|
||||
const PROVIDERS = ['bigcommerce', 'shopify', 'reactioncommerce']
|
||||
|
||||
function getProviderName() {
|
||||
// TODO: OSOT.
|
||||
|
2
framework/reactioncommerce/.env.template
Normal file
2
framework/reactioncommerce/.env.template
Normal file
@ -0,0 +1,2 @@
|
||||
SHOPIFY_STORE_DOMAIN=
|
||||
SHOPIFY_STOREFRONT_ACCESS_TOKEN=
|
260
framework/reactioncommerce/README.md
Normal file
260
framework/reactioncommerce/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,
|
||||
})
|
||||
```
|
93
framework/reactioncommerce/api/cart/handlers/add-item.ts
Normal file
93
framework/reactioncommerce/api/cart/handlers/add-item.ts
Normal file
@ -0,0 +1,93 @@
|
||||
import type { CartHandlers } from '..'
|
||||
import {
|
||||
addCartItemsMutation,
|
||||
checkoutCreateMutation,
|
||||
} from '@framework/utils/mutations'
|
||||
import getCartCookie from '@framework/api/utils/get-cart-cookie'
|
||||
import {
|
||||
REACTION_ANONYMOUS_CART_TOKEN_COOKIE,
|
||||
REACTION_CART_ID_COOKIE,
|
||||
} from '@framework/const'
|
||||
|
||||
const addItem: CartHandlers['addItem'] = async ({
|
||||
req: {
|
||||
cookies: {
|
||||
[REACTION_ANONYMOUS_CART_TOKEN_COOKIE]: anonymousCartToken,
|
||||
[REACTION_CART_ID_COOKIE]: cartId,
|
||||
},
|
||||
},
|
||||
res,
|
||||
body: { item },
|
||||
config,
|
||||
}) => {
|
||||
console.log('add-item API', item.productId)
|
||||
console.log('variantId', item.variantId)
|
||||
|
||||
if (!item) {
|
||||
return res.status(400).json({
|
||||
data: null,
|
||||
errors: [{ message: 'Missing item' }],
|
||||
})
|
||||
}
|
||||
if (!item.quantity) item.quantity = 1
|
||||
|
||||
if (cartId === config.dummyEmptyCartId) {
|
||||
const createdCart = await config.fetch(checkoutCreateMutation, {
|
||||
variables: {
|
||||
input: {
|
||||
shopId: config.shopId,
|
||||
items: [
|
||||
{
|
||||
productConfiguration: {
|
||||
productId: item.productId,
|
||||
productVariantId: item.variantId,
|
||||
},
|
||||
quantity: item.quantity,
|
||||
price: item.pricing,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
console.log('cart token', createdCart.data.createCart.token)
|
||||
console.log('created cart', createdCart.data.createCart.cart)
|
||||
|
||||
res.setHeader('Set-Cookie', [
|
||||
getCartCookie(config.cartCookie, createdCart.data.createCart.token, 999),
|
||||
getCartCookie(
|
||||
config.cartIdCookie,
|
||||
createdCart.data.createCart.cart._id,
|
||||
999
|
||||
),
|
||||
])
|
||||
return res.status(200).json(createdCart.data)
|
||||
} else if (cartId && anonymousCartToken) {
|
||||
const updatedCart = await config.fetch(addCartItemsMutation, {
|
||||
variables: {
|
||||
input: {
|
||||
cartId,
|
||||
cartToken: anonymousCartToken,
|
||||
items: [
|
||||
{
|
||||
productConfiguration: {
|
||||
productId: item.productId,
|
||||
productVariantId: item.variantId,
|
||||
},
|
||||
quantity: item.quantity,
|
||||
price: item.pricing,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
console.log('updatedCart', updatedCart)
|
||||
|
||||
return res.status(200).json(updatedCart.data)
|
||||
}
|
||||
|
||||
res.status(200)
|
||||
}
|
||||
|
||||
export default addItem
|
50
framework/reactioncommerce/api/cart/handlers/get-cart.ts
Normal file
50
framework/reactioncommerce/api/cart/handlers/get-cart.ts
Normal file
@ -0,0 +1,50 @@
|
||||
import type { Cart } from '../../../types'
|
||||
import type { CartHandlers } from '../'
|
||||
import getAnomymousCartQuery from '@framework/utils/queries/get-anonymous-cart'
|
||||
import getCartCookie from '@framework/api/utils/get-cart-cookie'
|
||||
import {
|
||||
REACTION_ANONYMOUS_CART_TOKEN_COOKIE,
|
||||
REACTION_CART_ID_COOKIE,
|
||||
} from '@framework/const.ts'
|
||||
import { normalizeCart } from '@framework/utils'
|
||||
|
||||
// Return current cart info
|
||||
const getCart: CartHandlers['getCart'] = async ({
|
||||
req: {
|
||||
cookies: {
|
||||
[REACTION_ANONYMOUS_CART_TOKEN_COOKIE]: anonymousCartToken,
|
||||
[REACTION_CART_ID_COOKIE]: cartId,
|
||||
},
|
||||
},
|
||||
res,
|
||||
config,
|
||||
}) => {
|
||||
let normalizedCart
|
||||
|
||||
console.log('get-cart API')
|
||||
console.log('anonymousCartToken', anonymousCartToken)
|
||||
console.log('cartId', cartId)
|
||||
console.log('shopId', config.shopId)
|
||||
|
||||
if (cartId && anonymousCartToken) {
|
||||
const {
|
||||
data: { cart: rawCart },
|
||||
} = await config.fetch(getAnomymousCartQuery, {
|
||||
variables: {
|
||||
cartId,
|
||||
cartToken: anonymousCartToken,
|
||||
},
|
||||
})
|
||||
|
||||
normalizedCart = normalizeCart(rawCart)
|
||||
} else {
|
||||
res.setHeader(
|
||||
'Set-Cookie',
|
||||
getCartCookie(config.cartCookie, config.dummyEmptyCartId, 999)
|
||||
)
|
||||
}
|
||||
|
||||
res.status(200).json({ data: normalizedCart ?? null })
|
||||
}
|
||||
|
||||
export default getCart
|
60
framework/reactioncommerce/api/cart/index.ts
Normal file
60
framework/reactioncommerce/api/cart/index.ts
Normal file
@ -0,0 +1,60 @@
|
||||
import isAllowedMethod from '../utils/is-allowed-method'
|
||||
import createApiHandler, {
|
||||
ReactionCommerceApiHandler,
|
||||
ReactionCommerceHandler,
|
||||
} from '../utils/create-api-handler'
|
||||
import { ReactionCommerceApiError } from '../utils/errors'
|
||||
import getCart from './handlers/get-cart'
|
||||
import addItem from './handlers/add-item'
|
||||
import type {
|
||||
Cart,
|
||||
GetCartHandlerBody,
|
||||
AddCartItemHandlerBody,
|
||||
} from '../../types'
|
||||
|
||||
export type CartHandlers = {
|
||||
getCart: ReactionCommerceHandler<Cart, GetCartHandlerBody>
|
||||
addItem: ReactionCommerceHandler<Cart, AddCartItemHandlerBody>
|
||||
}
|
||||
|
||||
const METHODS = ['GET', 'POST']
|
||||
|
||||
// TODO: a complete implementation should have schema validation for `req.body`
|
||||
const cartApi: ReactionCommerceApiHandler<Cart, CartHandlers> = async (
|
||||
req,
|
||||
res,
|
||||
config,
|
||||
handlers
|
||||
) => {
|
||||
if (!isAllowedMethod(req, res, METHODS)) return
|
||||
|
||||
const { cookies } = req
|
||||
const cartId = cookies[config.cartCookie]
|
||||
|
||||
try {
|
||||
// Return current cart info
|
||||
if (req.method === 'GET') {
|
||||
const body = { cartId }
|
||||
return await handlers['getCart']({ req, res, config, body })
|
||||
}
|
||||
|
||||
// Create or add an item to the cart
|
||||
if (req.method === 'POST') {
|
||||
const body = { ...req.body, cartId }
|
||||
return await handlers['addItem']({ req, res, config, body })
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
|
||||
const message =
|
||||
error instanceof ReactionCommerceApiError
|
||||
? 'An unexpected error occurred with the Reaction Commerce API'
|
||||
: 'An unexpected error occurred'
|
||||
|
||||
res.status(500).json({ data: null, errors: [{ message }] })
|
||||
}
|
||||
}
|
||||
|
||||
export const handlers = { getCart, addItem }
|
||||
|
||||
export default createApiHandler(cartApi, handlers, {})
|
1
framework/reactioncommerce/api/catalog/index.ts
Normal file
1
framework/reactioncommerce/api/catalog/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export default function () {}
|
1
framework/reactioncommerce/api/catalog/products.ts
Normal file
1
framework/reactioncommerce/api/catalog/products.ts
Normal file
@ -0,0 +1 @@
|
||||
export default function () {}
|
50
framework/reactioncommerce/api/checkout/index.ts
Normal file
50
framework/reactioncommerce/api/checkout/index.ts
Normal file
@ -0,0 +1,50 @@
|
||||
import isAllowedMethod from '../utils/is-allowed-method'
|
||||
import createApiHandler, {
|
||||
ReactionCommerceApiHandler,
|
||||
} from '../utils/create-api-handler'
|
||||
|
||||
import {
|
||||
REACTION_ANONYMOUS_CART_TOKEN_COOKIE,
|
||||
SHOPIFY_CHECKOUT_URL_COOKIE,
|
||||
SHOPIFY_CUSTOMER_TOKEN_COOKIE,
|
||||
} from '../../const'
|
||||
|
||||
import { getConfig } from '..'
|
||||
import associateCustomerWithCheckoutMutation from '../../utils/mutations/associate-customer-with-checkout'
|
||||
|
||||
const METHODS = ['GET']
|
||||
|
||||
const checkoutApi: ReactionCommerceApiHandler<any> = async (
|
||||
req,
|
||||
res,
|
||||
config
|
||||
) => {
|
||||
if (!isAllowedMethod(req, res, METHODS)) return
|
||||
|
||||
config = getConfig()
|
||||
|
||||
const { cookies } = req
|
||||
const checkoutUrl = cookies[SHOPIFY_CHECKOUT_URL_COOKIE]
|
||||
const customerCookie = cookies[SHOPIFY_CUSTOMER_TOKEN_COOKIE]
|
||||
|
||||
if (customerCookie) {
|
||||
try {
|
||||
await config.fetch(associateCustomerWithCheckoutMutation, {
|
||||
variables: {
|
||||
checkoutId: cookies[REACTION_ANONYMOUS_CART_TOKEN_COOKIE],
|
||||
customerAccessToken: cookies[SHOPIFY_CUSTOMER_TOKEN_COOKIE],
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
|
||||
if (checkoutUrl) {
|
||||
res.redirect(checkoutUrl)
|
||||
} else {
|
||||
res.redirect('/cart')
|
||||
}
|
||||
}
|
||||
|
||||
export default createApiHandler(checkoutApi, {}, {})
|
1
framework/reactioncommerce/api/customer.ts
Normal file
1
framework/reactioncommerce/api/customer.ts
Normal file
@ -0,0 +1 @@
|
||||
export default function () {}
|
1
framework/reactioncommerce/api/customers/index.ts
Normal file
1
framework/reactioncommerce/api/customers/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export default function () {}
|
1
framework/reactioncommerce/api/customers/login.ts
Normal file
1
framework/reactioncommerce/api/customers/login.ts
Normal file
@ -0,0 +1 @@
|
||||
export default function () {}
|
1
framework/reactioncommerce/api/customers/logout.ts
Normal file
1
framework/reactioncommerce/api/customers/logout.ts
Normal file
@ -0,0 +1 @@
|
||||
export default function () {}
|
1
framework/reactioncommerce/api/customers/signup.ts
Normal file
1
framework/reactioncommerce/api/customers/signup.ts
Normal file
@ -0,0 +1 @@
|
||||
export default function () {}
|
60
framework/reactioncommerce/api/index.ts
Normal file
60
framework/reactioncommerce/api/index.ts
Normal file
@ -0,0 +1,60 @@
|
||||
import type { CommerceAPIConfig } from '@commerce/api'
|
||||
|
||||
import {
|
||||
API_URL,
|
||||
REACTION_ANONYMOUS_CART_TOKEN_COOKIE,
|
||||
REACTION_CART_ID_COOKIE,
|
||||
REACTION_EMPTY_DUMMY_CART_ID,
|
||||
SHOPIFY_CUSTOMER_TOKEN_COOKIE,
|
||||
SHOPIFY_COOKIE_EXPIRE,
|
||||
SHOP_ID,
|
||||
} from '../const'
|
||||
|
||||
if (!API_URL) {
|
||||
throw new Error(
|
||||
`The environment variable NEXT_PUBLIC_SHOPIFY_STORE_DOMAIN is missing and it's required to access your store`
|
||||
)
|
||||
}
|
||||
|
||||
import fetchGraphqlApi from './utils/fetch-graphql-api'
|
||||
|
||||
export interface ReactionCommerceConfig extends CommerceAPIConfig {}
|
||||
|
||||
export class Config {
|
||||
private config: ReactionCommerceConfig
|
||||
|
||||
constructor(config: ReactionCommerceConfig) {
|
||||
this.config = config
|
||||
}
|
||||
|
||||
getConfig(userConfig: Partial<ReactionCommerceConfig> = {}) {
|
||||
return Object.entries(userConfig).reduce<ReactionCommerceConfig>(
|
||||
(cfg, [key, value]) => Object.assign(cfg, { [key]: value }),
|
||||
{ ...this.config }
|
||||
)
|
||||
}
|
||||
|
||||
setConfig(newConfig: Partial<ReactionCommerceConfig>) {
|
||||
Object.assign(this.config, newConfig)
|
||||
}
|
||||
}
|
||||
|
||||
const config = new Config({
|
||||
locale: 'en-US',
|
||||
commerceUrl: API_URL,
|
||||
cartCookie: REACTION_ANONYMOUS_CART_TOKEN_COOKIE,
|
||||
cartIdCookie: REACTION_CART_ID_COOKIE,
|
||||
dummyEmptyCartId: REACTION_EMPTY_DUMMY_CART_ID,
|
||||
cartCookieMaxAge: SHOPIFY_COOKIE_EXPIRE,
|
||||
fetch: fetchGraphqlApi,
|
||||
customerCookie: SHOPIFY_CUSTOMER_TOKEN_COOKIE,
|
||||
shopId: SHOP_ID,
|
||||
})
|
||||
|
||||
export function getConfig(userConfig?: Partial<ReactionCommerceConfig>) {
|
||||
return config.getConfig(userConfig)
|
||||
}
|
||||
|
||||
export function setConfig(newConfig: Partial<ReactionCommerceConfig>) {
|
||||
return config.setConfig(newConfig)
|
||||
}
|
25
framework/reactioncommerce/api/operations/get-page.ts
Normal file
25
framework/reactioncommerce/api/operations/get-page.ts
Normal file
@ -0,0 +1,25 @@
|
||||
import { Page } from '../../schema'
|
||||
import { ReactionCommerceConfig, 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?: ReactionCommerceConfig
|
||||
preview?: boolean
|
||||
}): Promise<GetPageResult> {
|
||||
config = getConfig(config)
|
||||
return {}
|
||||
}
|
||||
|
||||
export default getPage
|
60
framework/reactioncommerce/api/utils/create-api-handler.ts
Normal file
60
framework/reactioncommerce/api/utils/create-api-handler.ts
Normal file
@ -0,0 +1,60 @@
|
||||
import type { NextApiHandler, NextApiRequest, NextApiResponse } from 'next'
|
||||
import { ReactionCommerceConfig, getConfig } from '..'
|
||||
|
||||
export type ReactionCommerceApiHandler<
|
||||
T = any,
|
||||
H extends ReactionCommerceHandlers = {},
|
||||
Options extends {} = {}
|
||||
> = (
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse<ReactionCommerceApiResponse<T>>,
|
||||
config: ReactionCommerceConfig,
|
||||
handlers: H,
|
||||
// Custom configs that may be used by a particular handler
|
||||
options: Options
|
||||
) => void | Promise<void>
|
||||
|
||||
export type ReactionCommerceHandler<T = any, Body = null> = (options: {
|
||||
req: NextApiRequest
|
||||
res: NextApiResponse<ReactionCommerceApiResponse<T>>
|
||||
config: ReactionCommerceConfig
|
||||
body: Body
|
||||
}) => void | Promise<void>
|
||||
|
||||
export type ReactionCommerceHandlers<T = any> = {
|
||||
[k: string]: ReactionCommerceHandler<T, any>
|
||||
}
|
||||
|
||||
export type ReactionCommerceApiResponse<T> = {
|
||||
data: T | null
|
||||
errors?: { message: string; code?: string }[]
|
||||
}
|
||||
|
||||
export default function createApiHandler<
|
||||
T = any,
|
||||
H extends ReactionCommerceHandlers = {},
|
||||
Options extends {} = {}
|
||||
>(
|
||||
handler: ReactionCommerceApiHandler<T, H, Options>,
|
||||
handlers: H,
|
||||
defaultOptions: Options
|
||||
) {
|
||||
console.log('next api handler', defaultOptions)
|
||||
|
||||
return function getApiHandler({
|
||||
config,
|
||||
operations,
|
||||
options,
|
||||
}: {
|
||||
config?: ReactionCommerceConfig
|
||||
operations?: Partial<H>
|
||||
options?: Options extends {} ? Partial<Options> : never
|
||||
} = {}): NextApiHandler {
|
||||
const ops = { ...operations, ...handlers }
|
||||
const opts = { ...defaultOptions, ...options }
|
||||
|
||||
return function apiHandler(req, res) {
|
||||
return handler(req, res, getConfig(config), ops, opts)
|
||||
}
|
||||
}
|
||||
}
|
25
framework/reactioncommerce/api/utils/errors.ts
Normal file
25
framework/reactioncommerce/api/utils/errors.ts
Normal file
@ -0,0 +1,25 @@
|
||||
import type { Response } from '@vercel/fetch'
|
||||
|
||||
// Used for GraphQL errors
|
||||
export class ReactionCommerceGraphQLError extends Error {}
|
||||
|
||||
export class ReactionCommerceApiError extends Error {
|
||||
status: number
|
||||
res: Response
|
||||
data: any
|
||||
|
||||
constructor(msg: string, res: Response, data?: any) {
|
||||
super(msg)
|
||||
this.name = 'ReactionCommerceApiError'
|
||||
this.status = res.status
|
||||
this.res = res
|
||||
this.data = data
|
||||
}
|
||||
}
|
||||
|
||||
export class ReactionCommerceNetworkError extends Error {
|
||||
constructor(msg: string) {
|
||||
super(msg)
|
||||
this.name = 'ReactionCommerceNetworkError'
|
||||
}
|
||||
}
|
41
framework/reactioncommerce/api/utils/fetch-all-products.ts
Normal file
41
framework/reactioncommerce/api/utils/fetch-all-products.ts
Normal file
@ -0,0 +1,41 @@
|
||||
import { ProductEdge } from '../../schema'
|
||||
import { ReactionCommerceConfig } from '..'
|
||||
|
||||
const fetchAllProducts = async ({
|
||||
config,
|
||||
query,
|
||||
variables,
|
||||
acc = [],
|
||||
cursor,
|
||||
}: {
|
||||
config: ReactionCommerceConfig
|
||||
query: string
|
||||
acc?: ProductEdge[]
|
||||
variables?: any
|
||||
cursor?: string
|
||||
}): Promise<ProductEdge[]> => {
|
||||
const { data } = await config.fetch(query, {
|
||||
variables: { ...variables, cursor },
|
||||
})
|
||||
|
||||
const edges: ProductEdge[] = data.products?.edges ?? []
|
||||
const hasNextPage = data.products?.pageInfo?.hasNextPage
|
||||
acc = acc.concat(edges)
|
||||
|
||||
if (hasNextPage) {
|
||||
const cursor = edges.pop()?.cursor
|
||||
if (cursor) {
|
||||
return fetchAllProducts({
|
||||
config,
|
||||
query,
|
||||
variables,
|
||||
acc,
|
||||
cursor,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return acc
|
||||
}
|
||||
|
||||
export default fetchAllProducts
|
33
framework/reactioncommerce/api/utils/fetch-graphql-api.ts
Normal file
33
framework/reactioncommerce/api/utils/fetch-graphql-api.ts
Normal file
@ -0,0 +1,33 @@
|
||||
import type { GraphQLFetcher } from '@commerce/api'
|
||||
import fetch from './fetch'
|
||||
|
||||
import { API_URL } from '../../const'
|
||||
import { getError } from '../../utils/handle-fetch-response'
|
||||
|
||||
const fetchGraphqlApi: GraphQLFetcher = async (
|
||||
query: string,
|
||||
{ variables } = {},
|
||||
fetchOptions
|
||||
) => {
|
||||
const res = await fetch(API_URL, {
|
||||
...fetchOptions,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...fetchOptions?.headers,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query,
|
||||
variables,
|
||||
}),
|
||||
})
|
||||
|
||||
const { data, errors, status } = await res.json()
|
||||
|
||||
if (errors) {
|
||||
throw getError(errors, status)
|
||||
}
|
||||
|
||||
return { data, res }
|
||||
}
|
||||
export default fetchGraphqlApi
|
2
framework/reactioncommerce/api/utils/fetch.ts
Normal file
2
framework/reactioncommerce/api/utils/fetch.ts
Normal file
@ -0,0 +1,2 @@
|
||||
import zeitFetch from '@vercel/fetch'
|
||||
export default zeitFetch()
|
20
framework/reactioncommerce/api/utils/get-cart-cookie.ts
Normal file
20
framework/reactioncommerce/api/utils/get-cart-cookie.ts
Normal file
@ -0,0 +1,20 @@
|
||||
import { serialize, CookieSerializeOptions } from 'cookie'
|
||||
|
||||
export default function getCartCookie(
|
||||
name: string,
|
||||
cartId?: string,
|
||||
maxAge?: number
|
||||
) {
|
||||
const options: CookieSerializeOptions =
|
||||
cartId && maxAge
|
||||
? {
|
||||
maxAge,
|
||||
expires: new Date(Date.now() + maxAge * 1000),
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
path: '/',
|
||||
sameSite: 'lax',
|
||||
}
|
||||
: { maxAge: -1, path: '/' } // Removes the cookie
|
||||
|
||||
return serialize(name, cartId || '', options)
|
||||
}
|
28
framework/reactioncommerce/api/utils/is-allowed-method.ts
Normal file
28
framework/reactioncommerce/api/utils/is-allowed-method.ts
Normal file
@ -0,0 +1,28 @@
|
||||
import type { NextApiRequest, NextApiResponse } from 'next'
|
||||
|
||||
export default function isAllowedMethod(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse,
|
||||
allowedMethods: string[]
|
||||
) {
|
||||
const methods = allowedMethods.includes('OPTIONS')
|
||||
? allowedMethods
|
||||
: [...allowedMethods, 'OPTIONS']
|
||||
|
||||
if (!req.method || !methods.includes(req.method)) {
|
||||
res.status(405)
|
||||
res.setHeader('Allow', methods.join(', '))
|
||||
res.end()
|
||||
return false
|
||||
}
|
||||
|
||||
if (req.method === 'OPTIONS') {
|
||||
res.status(200)
|
||||
res.setHeader('Allow', methods.join(', '))
|
||||
res.setHeader('Content-Length', '0')
|
||||
res.end()
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
76
framework/reactioncommerce/auth/use-login.tsx
Normal file
76
framework/reactioncommerce/auth/use-login.tsx
Normal file
@ -0,0 +1,76 @@
|
||||
import { useCallback } from 'react'
|
||||
import type { MutationHook } from '@commerce/utils/types'
|
||||
import { CommerceError, ValidationError } from '@commerce/utils/errors'
|
||||
import useCustomer from '../customer/use-customer'
|
||||
import createCustomerAccessTokenMutation from '../utils/mutations/customer-access-token-create'
|
||||
import {
|
||||
CustomerAccessTokenCreateInput,
|
||||
CustomerUserError,
|
||||
Mutation,
|
||||
MutationCheckoutCreateArgs,
|
||||
} from '../schema'
|
||||
import useLogin, { UseLogin } from '@commerce/auth/use-login'
|
||||
import { setCustomerToken } from '../utils'
|
||||
|
||||
export default useLogin as UseLogin<typeof handler>
|
||||
|
||||
const getErrorMessage = ({ code, message }: CustomerUserError) => {
|
||||
switch (code) {
|
||||
case 'UNIDENTIFIED_CUSTOMER':
|
||||
message = 'Cannot find an account that matches the provided credentials'
|
||||
break
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
export const handler: MutationHook<null, {}, CustomerAccessTokenCreateInput> = {
|
||||
fetchOptions: {
|
||||
query: createCustomerAccessTokenMutation,
|
||||
},
|
||||
async fetcher({ input: { email, password }, options, fetch }) {
|
||||
if (!(email && password)) {
|
||||
throw new CommerceError({
|
||||
message:
|
||||
'A first name, last name, email and password are required to login',
|
||||
})
|
||||
}
|
||||
|
||||
const { customerAccessTokenCreate } = await fetch<
|
||||
Mutation,
|
||||
MutationCheckoutCreateArgs
|
||||
>({
|
||||
...options,
|
||||
variables: {
|
||||
input: { email, password },
|
||||
},
|
||||
})
|
||||
|
||||
const errors = customerAccessTokenCreate?.customerUserErrors
|
||||
|
||||
if (errors && errors.length) {
|
||||
throw new ValidationError({
|
||||
message: getErrorMessage(errors[0]),
|
||||
})
|
||||
}
|
||||
const customerAccessToken = customerAccessTokenCreate?.customerAccessToken
|
||||
const accessToken = customerAccessToken?.accessToken
|
||||
|
||||
if (accessToken) {
|
||||
setCustomerToken(accessToken)
|
||||
}
|
||||
|
||||
return null
|
||||
},
|
||||
useHook: ({ fetch }) => () => {
|
||||
const { revalidate } = useCustomer()
|
||||
|
||||
return useCallback(
|
||||
async function login(input) {
|
||||
const data = await fetch({ input })
|
||||
await revalidate()
|
||||
return data
|
||||
},
|
||||
[fetch, revalidate]
|
||||
)
|
||||
},
|
||||
}
|
36
framework/reactioncommerce/auth/use-logout.tsx
Normal file
36
framework/reactioncommerce/auth/use-logout.tsx
Normal file
@ -0,0 +1,36 @@
|
||||
import { useCallback } from 'react'
|
||||
import type { MutationHook } from '@commerce/utils/types'
|
||||
import useLogout, { UseLogout } from '@commerce/auth/use-logout'
|
||||
import useCustomer from '../customer/use-customer'
|
||||
import customerAccessTokenDeleteMutation from '../utils/mutations/customer-access-token-delete'
|
||||
import { getCustomerToken, setCustomerToken } from '../utils/customer-token'
|
||||
|
||||
export default useLogout as UseLogout<typeof handler>
|
||||
|
||||
export const handler: MutationHook<null> = {
|
||||
fetchOptions: {
|
||||
query: customerAccessTokenDeleteMutation,
|
||||
},
|
||||
async fetcher({ options, fetch }) {
|
||||
await fetch({
|
||||
...options,
|
||||
variables: {
|
||||
customerAccessToken: getCustomerToken(),
|
||||
},
|
||||
})
|
||||
setCustomerToken(null)
|
||||
return null
|
||||
},
|
||||
useHook: ({ fetch }) => () => {
|
||||
const { mutate } = useCustomer()
|
||||
|
||||
return useCallback(
|
||||
async function logout() {
|
||||
const data = await fetch()
|
||||
await mutate(null, false)
|
||||
return data
|
||||
},
|
||||
[fetch, mutate]
|
||||
)
|
||||
},
|
||||
}
|
74
framework/reactioncommerce/auth/use-signup.tsx
Normal file
74
framework/reactioncommerce/auth/use-signup.tsx
Normal file
@ -0,0 +1,74 @@
|
||||
import { useCallback } from 'react'
|
||||
import type { MutationHook } from '@commerce/utils/types'
|
||||
import { CommerceError } from '@commerce/utils/errors'
|
||||
import useSignup, { UseSignup } from '@commerce/auth/use-signup'
|
||||
import useCustomer from '../customer/use-customer'
|
||||
import { CustomerCreateInput } from '../schema'
|
||||
|
||||
import {
|
||||
customerCreateMutation,
|
||||
customerAccessTokenCreateMutation,
|
||||
} from '../utils/mutations'
|
||||
import handleLogin from '../utils/handle-login'
|
||||
|
||||
export default useSignup as UseSignup<typeof handler>
|
||||
|
||||
export const handler: MutationHook<
|
||||
null,
|
||||
{},
|
||||
CustomerCreateInput,
|
||||
CustomerCreateInput
|
||||
> = {
|
||||
fetchOptions: {
|
||||
query: customerCreateMutation,
|
||||
},
|
||||
async fetcher({
|
||||
input: { firstName, lastName, email, password },
|
||||
options,
|
||||
fetch,
|
||||
}) {
|
||||
if (!(firstName && lastName && email && password)) {
|
||||
throw new CommerceError({
|
||||
message:
|
||||
'A first name, last name, email and password are required to signup',
|
||||
})
|
||||
}
|
||||
const data = await fetch({
|
||||
...options,
|
||||
variables: {
|
||||
input: {
|
||||
firstName,
|
||||
lastName,
|
||||
email,
|
||||
password,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
try {
|
||||
const loginData = await fetch({
|
||||
query: customerAccessTokenCreateMutation,
|
||||
variables: {
|
||||
input: {
|
||||
email,
|
||||
password,
|
||||
},
|
||||
},
|
||||
})
|
||||
handleLogin(loginData)
|
||||
} catch (error) {}
|
||||
return data
|
||||
},
|
||||
useHook: ({ fetch }) => () => {
|
||||
const { revalidate } = useCustomer()
|
||||
|
||||
return useCallback(
|
||||
async function signup(input) {
|
||||
const data = await fetch({ input })
|
||||
await revalidate()
|
||||
return data
|
||||
},
|
||||
[fetch, revalidate]
|
||||
)
|
||||
},
|
||||
}
|
3
framework/reactioncommerce/cart/index.ts
Normal file
3
framework/reactioncommerce/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'
|
46
framework/reactioncommerce/cart/use-add-item.tsx
Normal file
46
framework/reactioncommerce/cart/use-add-item.tsx
Normal file
@ -0,0 +1,46 @@
|
||||
import { useCallback } from 'react'
|
||||
import type { MutationHook } from '@commerce/utils/types'
|
||||
import { CommerceError } from '@commerce/utils/errors'
|
||||
import useAddItem, { UseAddItem } from '@commerce/cart/use-add-item'
|
||||
import type { Cart, CartItemBody, AddCartItemBody } from '../types'
|
||||
import useCart from './use-cart'
|
||||
|
||||
export default useAddItem as UseAddItem<typeof handler>
|
||||
|
||||
export const handler: MutationHook<Cart, {}, CartItemBody> = {
|
||||
fetchOptions: {
|
||||
url: '/api/reactioncommerce/cart',
|
||||
method: 'POST',
|
||||
},
|
||||
async fetcher({ input: item, options, fetch }) {
|
||||
console.log('add cart item', item)
|
||||
|
||||
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<Cart, AddCartItemBody>({
|
||||
...options,
|
||||
body: { item },
|
||||
})
|
||||
|
||||
return data
|
||||
},
|
||||
useHook: ({ fetch }) => () => {
|
||||
const { mutate } = useCart()
|
||||
|
||||
return useCallback(
|
||||
async function addItem(input) {
|
||||
const data = await fetch({ input })
|
||||
await mutate(data, false)
|
||||
return data
|
||||
},
|
||||
[fetch, mutate]
|
||||
)
|
||||
},
|
||||
}
|
41
framework/reactioncommerce/cart/use-cart.tsx
Normal file
41
framework/reactioncommerce/cart/use-cart.tsx
Normal file
@ -0,0 +1,41 @@
|
||||
import { useMemo } from 'react'
|
||||
import { SWRHook } from '@commerce/utils/types'
|
||||
import useCart, { UseCart, FetchCartInput } from '@commerce/cart/use-cart'
|
||||
import type { Cart } from '../types'
|
||||
|
||||
export default useCart as UseCart<typeof handler>
|
||||
|
||||
export const handler: SWRHook<
|
||||
Cart | null,
|
||||
{},
|
||||
FetchCartInput,
|
||||
{ isEmpty?: boolean }
|
||||
> = {
|
||||
fetchOptions: {
|
||||
method: 'GET',
|
||||
url: '/api/reactioncommerce/cart',
|
||||
},
|
||||
async fetcher({ input: { cartId }, options, fetch }) {
|
||||
console.log('cart API fetcher', options)
|
||||
const data = await fetch(options)
|
||||
return data
|
||||
},
|
||||
useHook: ({ useData }) => (input) => {
|
||||
const response = useData({
|
||||
swrOptions: { revalidateOnFocus: false, ...input?.swrOptions },
|
||||
})
|
||||
|
||||
return useMemo(
|
||||
() =>
|
||||
Object.create(response, {
|
||||
isEmpty: {
|
||||
get() {
|
||||
return (response.data?.lineItems.length ?? 0) <= 0
|
||||
},
|
||||
enumerable: true,
|
||||
},
|
||||
}),
|
||||
[response]
|
||||
)
|
||||
},
|
||||
}
|
85
framework/reactioncommerce/cart/use-remove-item.tsx
Normal file
85
framework/reactioncommerce/cart/use-remove-item.tsx
Normal file
@ -0,0 +1,85 @@
|
||||
import { useCallback } from 'react'
|
||||
|
||||
import type {
|
||||
MutationHookContext,
|
||||
HookFetcherContext,
|
||||
} from '@commerce/utils/types'
|
||||
|
||||
import { ValidationError } from '@commerce/utils/errors'
|
||||
|
||||
import useRemoveItem, {
|
||||
RemoveItemInput as RemoveItemInputBase,
|
||||
UseRemoveItem,
|
||||
} from '@commerce/cart/use-remove-item'
|
||||
|
||||
import useCart from './use-cart'
|
||||
import {
|
||||
removeCartItemsMutation,
|
||||
getAnonymousCartToken,
|
||||
getCartId,
|
||||
normalizeCart,
|
||||
} from '../utils'
|
||||
import { Cart, LineItem } from '../types'
|
||||
import { Mutation, MutationUpdateCartItemsQuantityArgs } from '../schema'
|
||||
import { RemoveCartItemBody } from '@commerce/types'
|
||||
|
||||
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<RemoveItemInputBase>
|
||||
: RemoveItemInputBase
|
||||
|
||||
export default useRemoveItem as UseRemoveItem<typeof handler>
|
||||
|
||||
export const handler = {
|
||||
fetchOptions: {
|
||||
query: removeCartItemsMutation,
|
||||
},
|
||||
async fetcher({
|
||||
input: { itemId },
|
||||
options,
|
||||
fetch,
|
||||
}: HookFetcherContext<RemoveCartItemBody>) {
|
||||
const { removeCartItems } = await fetch<
|
||||
Mutation,
|
||||
MutationUpdateCartItemsQuantityArgs
|
||||
>({
|
||||
...options,
|
||||
variables: {
|
||||
input: {
|
||||
cartId: getCartId(),
|
||||
cartToken: getAnonymousCartToken(),
|
||||
cartItemIds: [itemId],
|
||||
},
|
||||
},
|
||||
})
|
||||
return normalizeCart(removeCartItems?.cart)
|
||||
},
|
||||
useHook: ({
|
||||
fetch,
|
||||
}: MutationHookContext<Cart | null, RemoveCartItemBody>) => <
|
||||
T extends LineItem | undefined = undefined
|
||||
>(
|
||||
ctx: { item?: T } = {}
|
||||
) => {
|
||||
const { item } = ctx
|
||||
const { mutate } = useCart()
|
||||
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 fetch({ input: { itemId } })
|
||||
await mutate(data, false)
|
||||
return data
|
||||
}
|
||||
|
||||
return useCallback(removeItem as RemoveItemFn<T>, [fetch, mutate])
|
||||
},
|
||||
}
|
116
framework/reactioncommerce/cart/use-update-item.tsx
Normal file
116
framework/reactioncommerce/cart/use-update-item.tsx
Normal file
@ -0,0 +1,116 @@
|
||||
import { useCallback } from 'react'
|
||||
import debounce from 'lodash.debounce'
|
||||
import type {
|
||||
HookFetcherContext,
|
||||
MutationHookContext,
|
||||
} from '@commerce/utils/types'
|
||||
import { ValidationError } from '@commerce/utils/errors'
|
||||
import useUpdateItem, {
|
||||
UpdateItemInput as UpdateItemInputBase,
|
||||
UseUpdateItem,
|
||||
} from '@commerce/cart/use-update-item'
|
||||
|
||||
import useCart from './use-cart'
|
||||
import { handler as removeItemHandler } from './use-remove-item'
|
||||
import type { Cart, LineItem, UpdateCartItemBody } from '../types'
|
||||
import {
|
||||
getAnonymousCartToken,
|
||||
getCartId,
|
||||
updateCartItemsQuantityMutation,
|
||||
normalizeCart,
|
||||
} from '../utils'
|
||||
import { Mutation, MutationUpdateCartItemsQuantityArgs } from '../schema'
|
||||
|
||||
export type UpdateItemInput<T = any> = T extends LineItem
|
||||
? Partial<UpdateItemInputBase<LineItem>>
|
||||
: UpdateItemInputBase<LineItem>
|
||||
|
||||
export default useUpdateItem as UseUpdateItem<typeof handler>
|
||||
|
||||
export const handler = {
|
||||
fetchOptions: {
|
||||
query: updateCartItemsQuantityMutation,
|
||||
},
|
||||
async fetcher({
|
||||
input: { itemId, item },
|
||||
options,
|
||||
fetch,
|
||||
}: HookFetcherContext<UpdateCartItemBody>) {
|
||||
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 removeItemHandler.fetcher({
|
||||
options: removeItemHandler.fetchOptions,
|
||||
input: {
|
||||
itemId,
|
||||
},
|
||||
fetch,
|
||||
})
|
||||
}
|
||||
} else if (item.quantity) {
|
||||
throw new ValidationError({
|
||||
message: 'The item quantity has to be a valid integer',
|
||||
})
|
||||
}
|
||||
const { updateCartItemsQuantity } = await fetch<
|
||||
Mutation,
|
||||
MutationUpdateCartItemsQuantityArgs
|
||||
>({
|
||||
...options,
|
||||
variables: {
|
||||
updateCartItemsQuantityInput: {
|
||||
cartId: getCartId(),
|
||||
cartToken: getAnonymousCartToken(),
|
||||
items: [
|
||||
{
|
||||
cartItemId: itemId,
|
||||
quantity: item.quantity,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return normalizeCart(updateCartItemsQuantity?.cart)
|
||||
},
|
||||
useHook: ({
|
||||
fetch,
|
||||
}: MutationHookContext<Cart | null, UpdateCartItemBody>) => <
|
||||
T extends LineItem | undefined = undefined
|
||||
>(
|
||||
ctx: {
|
||||
item?: T
|
||||
wait?: number
|
||||
} = {}
|
||||
) => {
|
||||
const { item } = ctx
|
||||
const { mutate } = useCart() as any
|
||||
|
||||
return useCallback(
|
||||
debounce(async (input: UpdateItemInput<T>) => {
|
||||
const itemId = input.id ?? item?.id
|
||||
const productId = input.productId ?? item?.productId
|
||||
const variantId = input.productId ?? item?.variantId
|
||||
if (!itemId || !productId || !variantId) {
|
||||
throw new ValidationError({
|
||||
message: 'Invalid input used for this operation',
|
||||
})
|
||||
}
|
||||
|
||||
const data = await fetch({
|
||||
input: {
|
||||
item: {
|
||||
productId,
|
||||
variantId,
|
||||
quantity: input.quantity,
|
||||
},
|
||||
itemId,
|
||||
},
|
||||
})
|
||||
await mutate(data, false)
|
||||
return data
|
||||
}, ctx.wait ?? 500),
|
||||
[fetch, mutate]
|
||||
)
|
||||
},
|
||||
}
|
34
framework/reactioncommerce/cart/utils/checkout-create.ts
Normal file
34
framework/reactioncommerce/cart/utils/checkout-create.ts
Normal file
@ -0,0 +1,34 @@
|
||||
import {
|
||||
REACTION_ANONYMOUS_CART_TOKEN_COOKIE,
|
||||
SHOPIFY_CHECKOUT_URL_COOKIE,
|
||||
SHOPIFY_COOKIE_EXPIRE,
|
||||
} from '../../const'
|
||||
|
||||
import checkoutCreateMutation from '../../utils/mutations/checkout-create'
|
||||
import Cookies from 'js-cookie'
|
||||
|
||||
export const checkoutCreate = async (fetch: any) => {
|
||||
const data = await fetch({
|
||||
query: checkoutCreateMutation,
|
||||
variables: {
|
||||
input: {
|
||||
shopId,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const checkout = data.checkoutCreate?.checkout
|
||||
const checkoutId = checkout?.id
|
||||
|
||||
if (checkoutId) {
|
||||
const options = {
|
||||
expires: SHOPIFY_COOKIE_EXPIRE,
|
||||
}
|
||||
Cookies.set(REACTION_ANONYMOUS_CART_TOKEN_COOKIE, checkoutId, options)
|
||||
Cookies.set(SHOPIFY_CHECKOUT_URL_COOKIE, checkout?.webUrl, options)
|
||||
}
|
||||
|
||||
return checkout
|
||||
}
|
||||
|
||||
export default checkoutCreate
|
31
framework/reactioncommerce/cart/utils/fetcher.ts
Normal file
31
framework/reactioncommerce/cart/utils/fetcher.ts
Normal file
@ -0,0 +1,31 @@
|
||||
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
|
2
framework/reactioncommerce/cart/utils/index.ts
Normal file
2
framework/reactioncommerce/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'
|
6
framework/reactioncommerce/commerce.config.json
Normal file
6
framework/reactioncommerce/commerce.config.json
Normal file
@ -0,0 +1,6 @@
|
||||
{
|
||||
"provider": "reactioncommerce",
|
||||
"features": {
|
||||
"wishlist": false
|
||||
}
|
||||
}
|
42
framework/reactioncommerce/common/get-all-pages.ts
Normal file
42
framework/reactioncommerce/common/get-all-pages.ts
Normal file
@ -0,0 +1,42 @@
|
||||
import { getConfig, ReactionCommerceConfig } from '../api'
|
||||
import { PageEdge } from '../schema'
|
||||
import { getAllPagesQuery } from '../utils/queries'
|
||||
|
||||
type Variables = {
|
||||
first?: number
|
||||
}
|
||||
|
||||
type ReturnType = {
|
||||
pages: Page[]
|
||||
}
|
||||
|
||||
export type Page = {
|
||||
id: string
|
||||
name: string
|
||||
url: string
|
||||
sort_order?: number
|
||||
body: string
|
||||
}
|
||||
|
||||
const getAllPages = async (options?: {
|
||||
variables?: Variables
|
||||
config: ReactionCommerceConfig
|
||||
preview?: boolean
|
||||
}): Promise<ReturnType> => {
|
||||
// let { config, variables = { first: 250 } } = options ?? {}
|
||||
// config = getConfig(config)
|
||||
// const { locale } = config
|
||||
// const { data } = await config.fetch(getAllPagesQuery, { variables })
|
||||
//
|
||||
// const pages = data.pages?.edges?.map(
|
||||
// ({ node: { title: name, handle, ...node } }: PageEdge) => ({
|
||||
// ...node,
|
||||
// url: `/${locale}/${handle}`,
|
||||
// name,
|
||||
// })
|
||||
// )
|
||||
|
||||
return { pages: [] }
|
||||
}
|
||||
|
||||
export default getAllPages
|
37
framework/reactioncommerce/common/get-page.ts
Normal file
37
framework/reactioncommerce/common/get-page.ts
Normal file
@ -0,0 +1,37 @@
|
||||
import { getConfig, ReactionCommerceConfig } from '../api'
|
||||
import getPageQuery from '../utils/queries/get-page-query'
|
||||
import { Page } from './get-all-pages'
|
||||
|
||||
type Variables = {
|
||||
id: string
|
||||
}
|
||||
|
||||
export type GetPageResult<T extends { page?: any } = { page?: Page }> = T
|
||||
|
||||
const getPage = async (options: {
|
||||
variables: Variables
|
||||
config: ReactionCommerceConfig
|
||||
preview?: boolean
|
||||
}): Promise<GetPageResult> => {
|
||||
let { config, variables } = options ?? {}
|
||||
|
||||
config = getConfig(config)
|
||||
const { locale } = config
|
||||
|
||||
const { data } = await config.fetch(getPageQuery, {
|
||||
variables,
|
||||
})
|
||||
const page = data.node
|
||||
|
||||
return {
|
||||
page: page
|
||||
? {
|
||||
...page,
|
||||
name: page.title,
|
||||
url: `/${locale}/${page.handle}`,
|
||||
}
|
||||
: null,
|
||||
}
|
||||
}
|
||||
|
||||
export default getPage
|
31
framework/reactioncommerce/common/get-site-info.ts
Normal file
31
framework/reactioncommerce/common/get-site-info.ts
Normal file
@ -0,0 +1,31 @@
|
||||
import getCategories, { Category } from '../utils/get-categories'
|
||||
import getVendors, { Brands } from '../utils/get-vendors'
|
||||
|
||||
import { getConfig, ReactionCommerceConfig } from '../api'
|
||||
|
||||
export type GetSiteInfoResult<
|
||||
T extends { categories: any[]; brands: any[] } = {
|
||||
categories: Category[]
|
||||
brands: Brands
|
||||
}
|
||||
> = T
|
||||
|
||||
const getSiteInfo = async (options?: {
|
||||
variables?: any
|
||||
config: ReactionCommerceConfig
|
||||
preview?: boolean
|
||||
}): Promise<GetSiteInfoResult> => {
|
||||
let { config } = options ?? {}
|
||||
|
||||
config = getConfig(config)
|
||||
|
||||
const categories = await getCategories(config)
|
||||
// const brands = await getVendors(config)
|
||||
|
||||
return {
|
||||
categories,
|
||||
brands: [],
|
||||
}
|
||||
}
|
||||
|
||||
export default getSiteInfo
|
18
framework/reactioncommerce/const.ts
Normal file
18
framework/reactioncommerce/const.ts
Normal file
@ -0,0 +1,18 @@
|
||||
export const REACTION_ANONYMOUS_CART_TOKEN_COOKIE =
|
||||
'reaction_anonymousCartToken'
|
||||
|
||||
export const REACTION_CART_ID_COOKIE = 'reaction_cartId'
|
||||
|
||||
export const REACTION_EMPTY_DUMMY_CART_ID = 'DUMMY_EMPTY_CART_ID'
|
||||
|
||||
export const SHOPIFY_CHECKOUT_URL_COOKIE = 'shopify_checkoutUrl'
|
||||
|
||||
export const SHOPIFY_CUSTOMER_TOKEN_COOKIE = 'shopify_customerToken'
|
||||
|
||||
export const STORE_DOMAIN = process.env.NEXT_PUBLIC_SHOPIFY_STORE_DOMAIN
|
||||
|
||||
export const SHOPIFY_COOKIE_EXPIRE = 30
|
||||
|
||||
export const API_URL = `http://127.0.0.1:3000/graphql`
|
||||
|
||||
export const SHOP_ID = 'cmVhY3Rpb24vc2hvcDplcnBESFlDdzc5cFRBV0FHUg=='
|
24
framework/reactioncommerce/customer/get-customer-id.ts
Normal file
24
framework/reactioncommerce/customer/get-customer-id.ts
Normal file
@ -0,0 +1,24 @@
|
||||
import { getConfig, ReactionCommerceConfig } from '../api'
|
||||
import getCustomerIdQuery from '../utils/queries/get-customer-id-query'
|
||||
import Cookies from 'js-cookie'
|
||||
|
||||
async function getCustomerId({
|
||||
customerToken: customerAccesToken,
|
||||
config,
|
||||
}: {
|
||||
customerToken: string
|
||||
config?: ReactionCommerceConfig
|
||||
}): Promise<number | undefined> {
|
||||
config = getConfig(config)
|
||||
|
||||
const { data } = await config.fetch(getCustomerIdQuery, {
|
||||
variables: {
|
||||
customerAccesToken:
|
||||
customerAccesToken || Cookies.get(config.customerCookie),
|
||||
},
|
||||
})
|
||||
|
||||
return data.customer?.id
|
||||
}
|
||||
|
||||
export default getCustomerId
|
1
framework/reactioncommerce/customer/index.ts
Normal file
1
framework/reactioncommerce/customer/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export { default as useCustomer } from './use-customer'
|
27
framework/reactioncommerce/customer/use-customer.tsx
Normal file
27
framework/reactioncommerce/customer/use-customer.tsx
Normal file
@ -0,0 +1,27 @@
|
||||
import useCustomer, { UseCustomer } from '@commerce/customer/use-customer'
|
||||
import { Customer } from '@commerce/types'
|
||||
import { SWRHook } from '@commerce/utils/types'
|
||||
import { getCustomerQuery, getCustomerToken } from '../utils'
|
||||
|
||||
export default useCustomer as UseCustomer<typeof handler>
|
||||
|
||||
export const handler: SWRHook<Customer | null> = {
|
||||
fetchOptions: {
|
||||
query: getCustomerQuery,
|
||||
},
|
||||
async fetcher({ options, fetch }) {
|
||||
const data = await fetch<any | null>({
|
||||
...options,
|
||||
variables: { customerAccessToken: getCustomerToken() },
|
||||
})
|
||||
return data.customer ?? null
|
||||
},
|
||||
useHook: ({ useData }) => (input) => {
|
||||
return useData({
|
||||
swrOptions: {
|
||||
revalidateOnFocus: false,
|
||||
...input?.swrOptions,
|
||||
},
|
||||
})
|
||||
},
|
||||
}
|
57
framework/reactioncommerce/fetcher.ts
Normal file
57
framework/reactioncommerce/fetcher.ts
Normal file
@ -0,0 +1,57 @@
|
||||
import { FetcherError } from '@commerce/utils/errors'
|
||||
import type { Fetcher } from '@commerce/utils/types'
|
||||
import { handleFetchResponse } from './utils'
|
||||
import { API_URL } from './const'
|
||||
|
||||
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 })
|
||||
}
|
||||
|
||||
const fetcher: Fetcher = async ({
|
||||
url,
|
||||
method = 'GET',
|
||||
variables,
|
||||
body: bodyObj,
|
||||
query,
|
||||
}) => {
|
||||
// if no URL is passed but we have a `query` param, we assume it's GraphQL
|
||||
if (!url && query) {
|
||||
return handleFetchResponse(
|
||||
await fetch(API_URL, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ query, variables }),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
const hasBody = Boolean(variables || bodyObj) && method !== 'GET'
|
||||
const body = hasBody
|
||||
? JSON.stringify(variables ? { variables } : bodyObj)
|
||||
: undefined
|
||||
const headers = hasBody ? { 'Content-Type': 'application/json' } : undefined
|
||||
const res = await fetch(url!, { method, body, headers })
|
||||
|
||||
if (res.ok) {
|
||||
const { data } = await res.json()
|
||||
return data
|
||||
}
|
||||
|
||||
throw await getError(res)
|
||||
}
|
||||
|
||||
export default fetcher
|
44
framework/reactioncommerce/index.tsx
Normal file
44
framework/reactioncommerce/index.tsx
Normal file
@ -0,0 +1,44 @@
|
||||
import * as React from 'react'
|
||||
import { ReactNode } from 'react'
|
||||
|
||||
import {
|
||||
CommerceConfig,
|
||||
CommerceProvider as CoreCommerceProvider,
|
||||
useCommerce as useCoreCommerce,
|
||||
} from '@commerce'
|
||||
|
||||
import { reactionCommerceProvider, ReactionCommerceProvider } from './provider'
|
||||
import { REACTION_ANONYMOUS_CART_TOKEN_COOKIE, SHOP_ID } from './const'
|
||||
|
||||
export { reactionCommerceProvider }
|
||||
export type { ReactionCommerceProvider }
|
||||
|
||||
export const reactionCommerceConfig: CommerceConfig = {
|
||||
locale: 'en-us',
|
||||
cartCookie: REACTION_ANONYMOUS_CART_TOKEN_COOKIE,
|
||||
shopId: SHOP_ID,
|
||||
}
|
||||
|
||||
export type ReactionCommerceConfig = Partial<CommerceConfig>
|
||||
|
||||
export type ReactionCommerceProps = {
|
||||
children?: ReactNode
|
||||
locale: string
|
||||
} & ReactionCommerceConfig
|
||||
|
||||
export function CommerceProvider({
|
||||
children,
|
||||
...config
|
||||
}: ReactionCommerceProps) {
|
||||
return (
|
||||
<CoreCommerceProvider
|
||||
// TODO: Fix this type
|
||||
provider={reactionCommerceProvider as any}
|
||||
config={{ ...reactionCommerceConfig, ...config }}
|
||||
>
|
||||
{children}
|
||||
</CoreCommerceProvider>
|
||||
)
|
||||
}
|
||||
|
||||
export const useCommerce = () => useCoreCommerce()
|
8
framework/reactioncommerce/next.config.js
Normal file
8
framework/reactioncommerce/next.config.js
Normal file
@ -0,0 +1,8 @@
|
||||
const commerce = require('./commerce.config.json')
|
||||
|
||||
module.exports = {
|
||||
commerce,
|
||||
images: {
|
||||
domains: ['localhost'],
|
||||
},
|
||||
}
|
29
framework/reactioncommerce/product/get-all-collections.ts
Normal file
29
framework/reactioncommerce/product/get-all-collections.ts
Normal file
@ -0,0 +1,29 @@
|
||||
import { CollectionEdge } from '../schema'
|
||||
import { getConfig, ReactionCommerceConfig } from '../api'
|
||||
import getAllCollectionsQuery from '../utils/queries/get-all-collections-query'
|
||||
|
||||
const getAllCollections = async (options?: {
|
||||
variables?: any
|
||||
config: ReactionCommerceConfig
|
||||
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
|
51
framework/reactioncommerce/product/get-all-product-paths.ts
Normal file
51
framework/reactioncommerce/product/get-all-product-paths.ts
Normal file
@ -0,0 +1,51 @@
|
||||
import { Product } from '@commerce/types'
|
||||
import { getConfig, ReactionCommerceConfig } from '../api'
|
||||
import fetchAllProducts from '../api/utils/fetch-all-products'
|
||||
import { ProductEdge } from '../schema'
|
||||
import getAllProductsPathsQuery from '../utils/queries/get-all-products-paths-query'
|
||||
|
||||
type ProductPath = {
|
||||
path: string
|
||||
}
|
||||
|
||||
export type ProductPathNode = {
|
||||
node: ProductPath
|
||||
}
|
||||
|
||||
type ReturnType = {
|
||||
products: ProductPathNode[]
|
||||
}
|
||||
|
||||
const getAllProductPaths = async (options?: {
|
||||
variables?: any
|
||||
config?: ReactionCommerceConfig
|
||||
preview?: boolean
|
||||
}): Promise<ReturnType> => {
|
||||
let { config, variables = { first: 250 } } = options ?? {}
|
||||
config = getConfig(config)
|
||||
|
||||
const products = await fetchAllProducts({
|
||||
config,
|
||||
query: getAllProductsPathsQuery,
|
||||
variables: {
|
||||
...variables,
|
||||
shopIds: [config.shopId],
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
products: products?.map(
|
||||
({
|
||||
node: {
|
||||
product: { slug },
|
||||
},
|
||||
}: CatalogItemEdge) => ({
|
||||
node: {
|
||||
path: `/${slug}`,
|
||||
},
|
||||
})
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
export default getAllProductPaths
|
42
framework/reactioncommerce/product/get-all-products.ts
Normal file
42
framework/reactioncommerce/product/get-all-products.ts
Normal file
@ -0,0 +1,42 @@
|
||||
import { GraphQLFetcherResult } from '@commerce/api'
|
||||
import { getConfig, ReactionCommerceConfig } from '../api'
|
||||
import { CatalogItemEdge } from '../schema'
|
||||
import { catalogItemsQuery } from '../utils/queries'
|
||||
import { normalizeProduct } from '../utils/normalize'
|
||||
import { Product } from '@commerce/types'
|
||||
|
||||
type Variables = {
|
||||
first?: number
|
||||
shopIds?: string[]
|
||||
}
|
||||
|
||||
type ReturnType = {
|
||||
products: CatalogItemConnection[]
|
||||
}
|
||||
|
||||
const getAllProducts = async (options: {
|
||||
variables?: Variables
|
||||
config?: ReactionCommerceConfig
|
||||
preview?: boolean
|
||||
}): Promise<ReturnType> => {
|
||||
let { config, variables = { first: 250 } } = options ?? {}
|
||||
config = getConfig(config)
|
||||
|
||||
const { data }: GraphQLFetcherResult = await config.fetch(catalogItemsQuery, {
|
||||
variables: {
|
||||
...variables,
|
||||
shopIds: [config.shopId],
|
||||
},
|
||||
})
|
||||
|
||||
const catalogItems =
|
||||
data.catalogItems?.edges?.map(({ node: p }: CatalogItemEdge) =>
|
||||
normalizeProduct(p)
|
||||
) ?? []
|
||||
|
||||
return {
|
||||
products: catalogItems,
|
||||
}
|
||||
}
|
||||
|
||||
export default getAllProducts
|
32
framework/reactioncommerce/product/get-product.ts
Normal file
32
framework/reactioncommerce/product/get-product.ts
Normal file
@ -0,0 +1,32 @@
|
||||
import { GraphQLFetcherResult } from '@commerce/api'
|
||||
import { getConfig, ReactionCommerceConfig } from '../api'
|
||||
import { normalizeProduct, getProductQuery } from '../utils'
|
||||
|
||||
type Variables = {
|
||||
slug: string
|
||||
}
|
||||
|
||||
type ReturnType = {
|
||||
product: any
|
||||
}
|
||||
|
||||
const getProduct = async (options: {
|
||||
variables: Variables
|
||||
config: ReactionCommerceConfig
|
||||
preview?: boolean
|
||||
}): Promise<ReturnType> => {
|
||||
let { config, variables } = options ?? {}
|
||||
config = getConfig(config)
|
||||
|
||||
const { data }: GraphQLFetcherResult = await config.fetch(getProductQuery, {
|
||||
variables,
|
||||
})
|
||||
|
||||
const { catalogItemProduct: product } = data
|
||||
|
||||
return {
|
||||
product: product ? normalizeProduct(product) : null,
|
||||
}
|
||||
}
|
||||
|
||||
export default getProduct
|
2
framework/reactioncommerce/product/use-price.tsx
Normal file
2
framework/reactioncommerce/product/use-price.tsx
Normal file
@ -0,0 +1,2 @@
|
||||
export * from '@commerce/product/use-price'
|
||||
export { default } from '@commerce/product/use-price'
|
80
framework/reactioncommerce/product/use-search.tsx
Normal file
80
framework/reactioncommerce/product/use-search.tsx
Normal file
@ -0,0 +1,80 @@
|
||||
import { SWRHook } from '@commerce/utils/types'
|
||||
import useSearch, { UseSearch } from '@commerce/product/use-search'
|
||||
|
||||
import { CatalogItemEdge } from '../schema'
|
||||
import {
|
||||
catalogItemsQuery,
|
||||
getCollectionProductsQuery,
|
||||
getSearchVariables,
|
||||
normalizeProduct,
|
||||
} from '../utils'
|
||||
|
||||
import { Product } from '@commerce/types'
|
||||
|
||||
export default useSearch as UseSearch<typeof handler>
|
||||
|
||||
export type SearchProductsInput = {
|
||||
search?: string
|
||||
categoryId?: string
|
||||
brandId?: string
|
||||
sort?: string
|
||||
shopId?: string
|
||||
}
|
||||
|
||||
export type SearchProductsData = {
|
||||
products: Product[]
|
||||
found: boolean
|
||||
}
|
||||
|
||||
export const handler: SWRHook<
|
||||
SearchProductsData,
|
||||
SearchProductsInput,
|
||||
SearchProductsInput
|
||||
> = {
|
||||
fetchOptions: {
|
||||
query: catalogItemsQuery,
|
||||
},
|
||||
async fetcher({ input, options, fetch }) {
|
||||
const { brandId, shopId } = input
|
||||
|
||||
const data = await fetch({
|
||||
query: options.query,
|
||||
method: options?.method,
|
||||
variables: {
|
||||
...getSearchVariables(input),
|
||||
shopIds: [shopId],
|
||||
},
|
||||
})
|
||||
|
||||
let edges
|
||||
|
||||
edges = data.catalogItems?.edges ?? []
|
||||
if (brandId) {
|
||||
edges = edges.filter(
|
||||
({ node: { vendor } }: CatalogItemEdge) => vendor === brandId
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
products: edges.map(({ node }: CatalogItemEdge) =>
|
||||
normalizeProduct(node)
|
||||
),
|
||||
found: !!edges.length,
|
||||
}
|
||||
},
|
||||
useHook: ({ useData }) => (input = {}) => {
|
||||
return useData({
|
||||
input: [
|
||||
['search', input.search],
|
||||
['categoryId', input.categoryId],
|
||||
['brandId', input.brandId],
|
||||
['sort', input.sort],
|
||||
['shopId', input.shopId],
|
||||
],
|
||||
swrOptions: {
|
||||
revalidateOnFocus: false,
|
||||
...input.swrOptions,
|
||||
},
|
||||
})
|
||||
},
|
||||
}
|
36
framework/reactioncommerce/provider.ts
Normal file
36
framework/reactioncommerce/provider.ts
Normal file
@ -0,0 +1,36 @@
|
||||
import {
|
||||
REACTION_ANONYMOUS_CART_TOKEN_COOKIE,
|
||||
REACTION_CART_ID_COOKIE,
|
||||
STORE_DOMAIN,
|
||||
} from './const'
|
||||
|
||||
import { handler as useCart } from './cart/use-cart'
|
||||
import { handler as useAddItem } from './cart/use-add-item'
|
||||
import { handler as useUpdateItem } from './cart/use-update-item'
|
||||
import { handler as useRemoveItem } from './cart/use-remove-item'
|
||||
|
||||
import { handler as useCustomer } from './customer/use-customer'
|
||||
import { handler as useSearch } from './product/use-search'
|
||||
|
||||
import { handler as useLogin } from './auth/use-login'
|
||||
import { handler as useLogout } from './auth/use-logout'
|
||||
import { handler as useSignup } from './auth/use-signup'
|
||||
|
||||
import fetcher from './fetcher'
|
||||
|
||||
export const reactionCommerceProvider = {
|
||||
locale: 'en-us',
|
||||
cartCookie: REACTION_ANONYMOUS_CART_TOKEN_COOKIE,
|
||||
cartIdCookie: REACTION_CART_ID_COOKIE,
|
||||
storeDomain: STORE_DOMAIN,
|
||||
fetcher,
|
||||
cart: { useCart, useAddItem, useUpdateItem, useRemoveItem },
|
||||
customer: { useCustomer },
|
||||
products: { useSearch },
|
||||
auth: { useLogin, useLogout, useSignup },
|
||||
features: {
|
||||
wishlist: false,
|
||||
},
|
||||
}
|
||||
|
||||
export type ReactionCommerceProvider = typeof reactionCommerceProvider
|
7593
framework/reactioncommerce/schema.d.ts
vendored
Normal file
7593
framework/reactioncommerce/schema.d.ts
vendored
Normal file
File diff suppressed because it is too large
Load Diff
14126
framework/reactioncommerce/schema.graphql
Normal file
14126
framework/reactioncommerce/schema.graphql
Normal file
File diff suppressed because it is too large
Load Diff
45
framework/reactioncommerce/types.ts
Normal file
45
framework/reactioncommerce/types.ts
Normal file
@ -0,0 +1,45 @@
|
||||
import * as Core from '@commerce/types'
|
||||
import { CheckoutLineItem } from './schema'
|
||||
|
||||
export type ShopifyCheckout = {
|
||||
id: string
|
||||
webUrl: string
|
||||
lineItems: CheckoutLineItem[]
|
||||
}
|
||||
|
||||
export interface Cart extends Core.Cart {
|
||||
id: string
|
||||
lineItems: LineItem[]
|
||||
}
|
||||
|
||||
export interface LineItem extends Core.LineItem {
|
||||
options: any[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Cart mutations
|
||||
*/
|
||||
|
||||
export type OptionSelections = {
|
||||
option_id: number
|
||||
option_value: number | string
|
||||
}
|
||||
|
||||
export type CartItemBody = Core.CartItemBody & {
|
||||
productId: string // The product id is always required for BC
|
||||
optionSelections?: OptionSelections
|
||||
}
|
||||
|
||||
export type GetCartHandlerBody = Core.GetCartHandlerBody
|
||||
|
||||
export type AddCartItemBody = Core.AddCartItemBody<CartItemBody>
|
||||
|
||||
export type AddCartItemHandlerBody = Core.AddCartItemHandlerBody<CartItemBody>
|
||||
|
||||
export type UpdateCartItemBody = Core.UpdateCartItemBody<CartItemBody>
|
||||
|
||||
export type UpdateCartItemHandlerBody = Core.UpdateCartItemHandlerBody<CartItemBody>
|
||||
|
||||
export type RemoveCartItemBody = Core.RemoveCartItemBody
|
||||
|
||||
export type RemoveCartItemHandlerBody = Core.RemoveCartItemHandlerBody
|
21
framework/reactioncommerce/utils/customer-token.ts
Normal file
21
framework/reactioncommerce/utils/customer-token.ts
Normal file
@ -0,0 +1,21 @@
|
||||
import Cookies, { CookieAttributes } from 'js-cookie'
|
||||
import { SHOPIFY_COOKIE_EXPIRE, SHOPIFY_CUSTOMER_TOKEN_COOKIE } from '../const'
|
||||
|
||||
export const getCustomerToken = () => Cookies.get(SHOPIFY_CUSTOMER_TOKEN_COOKIE)
|
||||
|
||||
export const setCustomerToken = (
|
||||
token: string | null,
|
||||
options?: CookieAttributes
|
||||
) => {
|
||||
if (!token) {
|
||||
Cookies.remove(SHOPIFY_CUSTOMER_TOKEN_COOKIE)
|
||||
} else {
|
||||
Cookies.set(
|
||||
SHOPIFY_CUSTOMER_TOKEN_COOKIE,
|
||||
token,
|
||||
options ?? {
|
||||
expires: SHOPIFY_COOKIE_EXPIRE,
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
import Cookies from 'js-cookie'
|
||||
import { REACTION_ANONYMOUS_CART_TOKEN_COOKIE } from '../const'
|
||||
|
||||
const getAnonymousCartToken = (id?: string) => {
|
||||
return id ?? Cookies.get(REACTION_ANONYMOUS_CART_TOKEN_COOKIE)
|
||||
}
|
||||
|
||||
export default getAnonymousCartToken
|
8
framework/reactioncommerce/utils/get-cart-id.ts
Normal file
8
framework/reactioncommerce/utils/get-cart-id.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import Cookies from 'js-cookie'
|
||||
import { REACTION_CART_ID_COOKIE } from '../const'
|
||||
|
||||
const getCartId = (id?: string) => {
|
||||
return id ?? Cookies.get(REACTION_CART_ID_COOKIE)
|
||||
}
|
||||
|
||||
export default getCartId
|
34
framework/reactioncommerce/utils/get-categories.ts
Normal file
34
framework/reactioncommerce/utils/get-categories.ts
Normal file
@ -0,0 +1,34 @@
|
||||
import { ReactionCommerceConfig } from '../api'
|
||||
import { CollectionEdge, TagEdge } from '../schema'
|
||||
import getTagsQuery from './queries/get-all-collections-query'
|
||||
|
||||
export type Category = {
|
||||
entityId: string
|
||||
name: string
|
||||
path: string
|
||||
}
|
||||
|
||||
const getCategories = async (
|
||||
config: ReactionCommerceConfig
|
||||
): Promise<Tag[]> => {
|
||||
const { data } = await config.fetch(getTagsQuery, {
|
||||
variables: {
|
||||
first: 250,
|
||||
shopId: config.shopId,
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
data.tags?.edges?.map(
|
||||
({
|
||||
node: { _id: entityId, displayTitle: name, slug: handle },
|
||||
}: TagEdge) => ({
|
||||
entityId,
|
||||
name,
|
||||
path: `/${handle}`,
|
||||
})
|
||||
) ?? []
|
||||
)
|
||||
}
|
||||
|
||||
export default getCategories
|
35
framework/reactioncommerce/utils/get-search-variables.ts
Normal file
35
framework/reactioncommerce/utils/get-search-variables.ts
Normal file
@ -0,0 +1,35 @@
|
||||
import getSortVariables from './get-sort-variables'
|
||||
import type { SearchProductsInput } from '../product/use-search'
|
||||
|
||||
export const getSearchVariables = ({
|
||||
brandId,
|
||||
search,
|
||||
categoryId,
|
||||
sort,
|
||||
}: SearchProductsInput) => {
|
||||
let query = ''
|
||||
let tagIdsParam = {}
|
||||
|
||||
if (search) {
|
||||
query += `product_type:${search} OR title:${search} OR tag:${search}`
|
||||
}
|
||||
|
||||
if (brandId) {
|
||||
query += `${search ? ' AND ' : ''}vendor:${brandId}`
|
||||
}
|
||||
|
||||
if (categoryId) {
|
||||
tagIdsParam = {
|
||||
tagIds: [categoryId],
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
// categoryId,
|
||||
// query,
|
||||
...tagIdsParam,
|
||||
...getSortVariables(sort, !!categoryId),
|
||||
}
|
||||
}
|
||||
|
||||
export default getSearchVariables
|
32
framework/reactioncommerce/utils/get-sort-variables.ts
Normal file
32
framework/reactioncommerce/utils/get-sort-variables.ts
Normal file
@ -0,0 +1,32 @@
|
||||
const getSortVariables = (sort?: string, isCategory = false) => {
|
||||
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: isCategory ? 'CREATED' : 'CREATED_AT',
|
||||
reverse: true,
|
||||
}
|
||||
break
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
export default getSortVariables
|
38
framework/reactioncommerce/utils/get-vendors.ts
Normal file
38
framework/reactioncommerce/utils/get-vendors.ts
Normal file
@ -0,0 +1,38 @@
|
||||
import { ReactionCommerceConfig } from '../api'
|
||||
import fetchAllProducts from '../api/utils/fetch-all-products'
|
||||
import getAllProductVendors from './queries/get-all-product-vendors-query'
|
||||
|
||||
export type BrandNode = {
|
||||
name: string
|
||||
path: string
|
||||
}
|
||||
|
||||
export type BrandEdge = {
|
||||
node: BrandNode
|
||||
}
|
||||
|
||||
export type Brands = BrandEdge[]
|
||||
|
||||
const getVendors = async (
|
||||
config: ReactionCommerceConfig
|
||||
): Promise<BrandEdge[]> => {
|
||||
const vendors = await fetchAllProducts({
|
||||
config,
|
||||
query: getAllProductVendors,
|
||||
variables: {
|
||||
first: 250,
|
||||
},
|
||||
})
|
||||
|
||||
let vendorsStrings = vendors.map(({ node: { vendor } }) => vendor)
|
||||
|
||||
return [...new Set(vendorsStrings)].map((v) => ({
|
||||
node: {
|
||||
entityId: v,
|
||||
name: v,
|
||||
path: `brands/${v}`,
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
export default getVendors
|
27
framework/reactioncommerce/utils/handle-fetch-response.ts
Normal file
27
framework/reactioncommerce/utils/handle-fetch-response.ts
Normal file
@ -0,0 +1,27 @@
|
||||
import { FetcherError } from '@commerce/utils/errors'
|
||||
|
||||
export function getError(errors: any[], status: number) {
|
||||
errors = errors ?? [{ message: 'Failed to fetch Shopify API' }]
|
||||
return new FetcherError({ errors, status })
|
||||
}
|
||||
|
||||
export async function getAsyncError(res: Response) {
|
||||
const data = await res.json()
|
||||
return getError(data.errors, res.status)
|
||||
}
|
||||
|
||||
const handleFetchResponse = async (res: Response) => {
|
||||
if (res.ok) {
|
||||
const { data, errors } = await res.json()
|
||||
|
||||
if (errors && errors.length) {
|
||||
throw getError(errors, res.status)
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
throw await getAsyncError(res)
|
||||
}
|
||||
|
||||
export default handleFetchResponse
|
39
framework/reactioncommerce/utils/handle-login.ts
Normal file
39
framework/reactioncommerce/utils/handle-login.ts
Normal file
@ -0,0 +1,39 @@
|
||||
import { ValidationError } from '@commerce/utils/errors'
|
||||
import { setCustomerToken } from './customer-token'
|
||||
|
||||
const getErrorMessage = ({
|
||||
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 response = data.customerAccessTokenCreate
|
||||
const errors = response?.customerUserErrors
|
||||
|
||||
if (errors && errors.length) {
|
||||
throw new ValidationError({
|
||||
message: getErrorMessage(errors[0]),
|
||||
})
|
||||
}
|
||||
|
||||
const customerAccessToken = response?.customerAccessToken
|
||||
const accessToken = customerAccessToken?.accessToken
|
||||
|
||||
if (accessToken) {
|
||||
setCustomerToken(accessToken)
|
||||
}
|
||||
|
||||
return customerAccessToken
|
||||
}
|
||||
|
||||
export default handleLogin
|
11
framework/reactioncommerce/utils/index.ts
Normal file
11
framework/reactioncommerce/utils/index.ts
Normal file
@ -0,0 +1,11 @@
|
||||
export { default as handleFetchResponse } from './handle-fetch-response'
|
||||
export { default as getSearchVariables } from './get-search-variables'
|
||||
export { default as getSortVariables } from './get-sort-variables'
|
||||
export { default as getVendors } from './get-vendors'
|
||||
export { default as getCategories } from './get-categories'
|
||||
export { default as getAnonymousCartToken } from './get-anonymous-cart-token'
|
||||
export { default as getCartId } from './get-cart-id'
|
||||
export * from './queries'
|
||||
export * from './mutations'
|
||||
export * from './normalize'
|
||||
export * from './customer-token'
|
24
framework/reactioncommerce/utils/mutations/add-cart-items.ts
Normal file
24
framework/reactioncommerce/utils/mutations/add-cart-items.ts
Normal file
@ -0,0 +1,24 @@
|
||||
import {
|
||||
cartPayloadFragment,
|
||||
incorrectPriceFailureDetailsFragment,
|
||||
minOrderQuantityFailureDetailsFragment,
|
||||
} from '@framework/utils/queries/get-checkout-query'
|
||||
|
||||
const addCartItemsMutation = `
|
||||
mutation addCartItemsMutation($input: AddCartItemsInput!) {
|
||||
addCartItems(input: $input) {
|
||||
cart {
|
||||
${cartPayloadFragment}
|
||||
}
|
||||
incorrectPriceFailures {
|
||||
${incorrectPriceFailureDetailsFragment}
|
||||
}
|
||||
minOrderQuantityFailures {
|
||||
${minOrderQuantityFailureDetailsFragment}
|
||||
}
|
||||
clientMutationId
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export default addCartItemsMutation
|
@ -0,0 +1,18 @@
|
||||
const associateCustomerWithCheckoutMutation = /* GraphQl */ `
|
||||
mutation associateCustomerWithCheckout($checkoutId: ID!, $customerAccessToken: String!) {
|
||||
checkoutCustomerAssociateV2(checkoutId: $checkoutId, customerAccessToken: $customerAccessToken) {
|
||||
checkout {
|
||||
id
|
||||
}
|
||||
checkoutUserErrors {
|
||||
code
|
||||
field
|
||||
message
|
||||
}
|
||||
customer {
|
||||
id
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
export default associateCustomerWithCheckoutMutation
|
@ -0,0 +1,24 @@
|
||||
import {
|
||||
cartPayloadFragment,
|
||||
incorrectPriceFailureDetailsFragment,
|
||||
minOrderQuantityFailureDetailsFragment,
|
||||
} from '@framework/utils/queries/get-checkout-query'
|
||||
|
||||
const checkoutCreateMutation = /* GraphQL */ `
|
||||
mutation createCartMutation($input: CreateCartInput!) {
|
||||
createCart(input: $input) {
|
||||
cart {
|
||||
${cartPayloadFragment}
|
||||
}
|
||||
incorrectPriceFailures {
|
||||
${incorrectPriceFailureDetailsFragment}
|
||||
}
|
||||
minOrderQuantityFailures {
|
||||
${minOrderQuantityFailureDetailsFragment}
|
||||
}
|
||||
clientMutationId
|
||||
token
|
||||
}
|
||||
}
|
||||
`
|
||||
export default checkoutCreateMutation
|
@ -0,0 +1,16 @@
|
||||
const customerAccessTokenCreateMutation = /* GraphQL */ `
|
||||
mutation customerAccessTokenCreate($input: CustomerAccessTokenCreateInput!) {
|
||||
customerAccessTokenCreate(input: $input) {
|
||||
customerAccessToken {
|
||||
accessToken
|
||||
expiresAt
|
||||
}
|
||||
customerUserErrors {
|
||||
code
|
||||
field
|
||||
message
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
export default customerAccessTokenCreateMutation
|
@ -0,0 +1,14 @@
|
||||
const customerAccessTokenDeleteMutation = /* GraphQL */ `
|
||||
mutation customerAccessTokenDelete($customerAccessToken: String!) {
|
||||
customerAccessTokenDelete(customerAccessToken: $customerAccessToken) {
|
||||
deletedAccessToken
|
||||
deletedCustomerAccessTokenId
|
||||
userErrors {
|
||||
field
|
||||
message
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export default customerAccessTokenDeleteMutation
|
@ -0,0 +1,15 @@
|
||||
const customerCreateMutation = /* GraphQL */ `
|
||||
mutation customerCreate($input: CustomerCreateInput!) {
|
||||
customerCreate(input: $input) {
|
||||
customerUserErrors {
|
||||
code
|
||||
field
|
||||
message
|
||||
}
|
||||
customer {
|
||||
id
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
export default customerCreateMutation
|
7
framework/reactioncommerce/utils/mutations/index.ts
Normal file
7
framework/reactioncommerce/utils/mutations/index.ts
Normal file
@ -0,0 +1,7 @@
|
||||
export { default as addCartItemsMutation } from './add-cart-items'
|
||||
export { default as customerCreateMutation } from './customer-create'
|
||||
export { default as checkoutCreateMutation } from './checkout-create'
|
||||
export { default as customerAccessTokenCreateMutation } from './customer-access-token-create'
|
||||
export { default as customerAccessTokenDeleteMutation } from './customer-access-token-delete'
|
||||
export { default as removeCartItemsMutation } from './remove-cart-items'
|
||||
export { default as updateCartItemsQuantityMutation } from './update-cart-items-quantity'
|
@ -0,0 +1,13 @@
|
||||
import { cartPayloadFragment } from '@framework/utils/queries/get-checkout-query'
|
||||
|
||||
const updateCartItemsQuantityMutation = `
|
||||
mutation removeCartItemsMutation($input: RemoveCartItemsInput!) {
|
||||
removeCartItems(input: $input) {
|
||||
cart {
|
||||
${cartPayloadFragment}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export default updateCartItemsQuantityMutation
|
@ -0,0 +1,13 @@
|
||||
import { cartPayloadFragment } from '@framework/utils/queries/get-checkout-query'
|
||||
|
||||
const updateCartItemsQuantityMutation = `
|
||||
mutation UpdateCartItemsQuantity($updateCartItemsQuantityInput: UpdateCartItemsQuantityInput!) {
|
||||
updateCartItemsQuantity(input: $updateCartItemsQuantityInput) {
|
||||
cart {
|
||||
${cartPayloadFragment}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export default updateCartItemsQuantityMutation
|
218
framework/reactioncommerce/utils/normalize.ts
Normal file
218
framework/reactioncommerce/utils/normalize.ts
Normal file
@ -0,0 +1,218 @@
|
||||
import { Product } from '@commerce/types'
|
||||
|
||||
import {
|
||||
CatalogItem,
|
||||
Cart as ReactionCart,
|
||||
ProductPricingInfo,
|
||||
CatalogProductVariant,
|
||||
CartItemEdge,
|
||||
} from '../schema'
|
||||
|
||||
import type { Cart, LineItem } from '../types'
|
||||
|
||||
const money = ({ displayPrice }: ProductPricingInfo) => {
|
||||
return {
|
||||
displayPrice,
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeProductOption = ({
|
||||
id,
|
||||
name: displayName,
|
||||
values,
|
||||
}: ProductOption) => {
|
||||
return {
|
||||
__typename: 'MultipleChoiceOption',
|
||||
id,
|
||||
displayName,
|
||||
values: values.map((value) => {
|
||||
let output: any = {
|
||||
label: value,
|
||||
}
|
||||
if (displayName === 'Color') {
|
||||
output = {
|
||||
...output,
|
||||
hexColors: [value],
|
||||
}
|
||||
}
|
||||
return output
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeProductVariants = (variants: [CatalogProductVariant]) => {
|
||||
return variants?.map(
|
||||
({
|
||||
variantId,
|
||||
attributeLabel,
|
||||
optionTitle,
|
||||
options,
|
||||
sku,
|
||||
title,
|
||||
pricing,
|
||||
}) => {
|
||||
const variantPrice = pricing[0]?.price ?? pricing[0]?.minPrice
|
||||
|
||||
return {
|
||||
id: variantId,
|
||||
name: title,
|
||||
sku: sku ?? variantId,
|
||||
price: variantPrice,
|
||||
listPrice: pricing[0]?.compareAtPrice?.amount ?? variantPrice,
|
||||
requiresShipping: true,
|
||||
// options: options?.map(({ attributeLabel, optionTitle }: CatalogProductVariant) =>
|
||||
// normalizeProductOption({
|
||||
// id: _id,
|
||||
// name: attributeLabel,
|
||||
// values: [optionTitle],
|
||||
// })
|
||||
// ) ?? [],
|
||||
options: [
|
||||
{
|
||||
__typename: 'MultipleChoiceOption',
|
||||
displayName: attributeLabel,
|
||||
values: [{ label: optionTitle }],
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
export function groupProductOptionsByAttributeLabel(
|
||||
options: [CatalogProductVariant]
|
||||
) {
|
||||
return options.reduce((groupedOptions, currentOption) => {
|
||||
const attributeLabelIndex = groupedOptions.findIndex((option) => {
|
||||
return (
|
||||
option.displayName.toLowerCase() ===
|
||||
currentOption.attributeLabel.toLowerCase()
|
||||
)
|
||||
})
|
||||
|
||||
if (attributeLabelIndex !== -1) {
|
||||
groupedOptions[attributeLabelIndex].values = [
|
||||
...groupedOptions[attributeLabelIndex].values,
|
||||
{
|
||||
label: currentOption.optionTitle,
|
||||
hexColors: [currentOption.optionTitle],
|
||||
},
|
||||
]
|
||||
} else {
|
||||
groupedOptions = [
|
||||
...groupedOptions,
|
||||
normalizeProductOption({
|
||||
id: currentOption.variantId,
|
||||
name: currentOption.attributeLabel,
|
||||
values: [currentOption.optionTitle],
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
return groupedOptions
|
||||
}, [])
|
||||
}
|
||||
|
||||
export function normalizeProduct(productNode: CatalogItemEdge): CatalogItem {
|
||||
const {
|
||||
_id,
|
||||
product: {
|
||||
productId,
|
||||
description,
|
||||
title: name,
|
||||
vendor,
|
||||
pricing,
|
||||
slug,
|
||||
primaryImage,
|
||||
variants,
|
||||
},
|
||||
...rest
|
||||
} = productNode
|
||||
|
||||
const product = {
|
||||
id: productId ?? _id,
|
||||
name,
|
||||
vendor,
|
||||
description,
|
||||
path: `/${slug}`,
|
||||
slug: slug?.replace(/^\/+|\/+$/g, ''),
|
||||
price: {
|
||||
value: pricing[0].minPrice,
|
||||
currencyCode: pricing[0].currency.code,
|
||||
},
|
||||
variants: variants ? normalizeProductVariants(variants) : [],
|
||||
options: variants ? groupProductOptionsByAttributeLabel(variants) : [],
|
||||
images: [],
|
||||
...rest,
|
||||
}
|
||||
|
||||
if (productNode.product.primaryImage) {
|
||||
product.images = [
|
||||
{
|
||||
url: primaryImage?.URLs?.original,
|
||||
alt: name,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
return product
|
||||
}
|
||||
|
||||
export function normalizeCart(cart: ReactionCart): Cart {
|
||||
return {
|
||||
id: cart._id,
|
||||
customerId: '',
|
||||
email: '',
|
||||
createdAt: cart.createdAt,
|
||||
currency: {
|
||||
code: cart.checkout?.summary?.total?.currency.code,
|
||||
},
|
||||
taxesIncluded: false,
|
||||
lineItems: cart.items?.edges?.map(normalizeLineItem),
|
||||
lineItemsSubtotalPrice: +cart.checkout?.summary?.itemTotal?.amount,
|
||||
subtotalPrice: +cart.checkout?.summary?.itemTotal?.amount,
|
||||
totalPrice: cart.checkout?.summary?.total?.amount,
|
||||
discounts: [],
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeLineItem({
|
||||
node: {
|
||||
_id,
|
||||
compareAtPrice,
|
||||
imageURLs,
|
||||
title,
|
||||
productConfiguration,
|
||||
priceWhenAdded,
|
||||
optionTitle,
|
||||
variantTitle,
|
||||
quantity,
|
||||
},
|
||||
}: CartItemEdge): LineItem {
|
||||
console.log('imageURLs', imageURLs)
|
||||
return {
|
||||
id: _id,
|
||||
variantId: String(productConfiguration?.productVariantId),
|
||||
productId: String(productConfiguration?.productId),
|
||||
name: `${title}`,
|
||||
quantity,
|
||||
variant: {
|
||||
id: String(productConfiguration?.productVariantId),
|
||||
sku: String(productConfiguration?.productVariantId),
|
||||
name: String(optionTitle || variantTitle),
|
||||
image: {
|
||||
url: imageURLs?.original ?? '/product-img-placeholder.svg',
|
||||
},
|
||||
requiresShipping: true,
|
||||
price: priceWhenAdded?.amount,
|
||||
listPrice: compareAtPrice?.amount,
|
||||
},
|
||||
path: '',
|
||||
discounts: [],
|
||||
options: [
|
||||
{
|
||||
value: String(optionTitle || variantTitle),
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
@ -0,0 +1,67 @@
|
||||
export const catalogItemsConnection = `
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
hasPreviousPage
|
||||
}
|
||||
edges {
|
||||
node {
|
||||
_id
|
||||
... on CatalogItemProduct {
|
||||
product {
|
||||
_id
|
||||
title
|
||||
slug
|
||||
description
|
||||
vendor
|
||||
isLowQuantity
|
||||
isSoldOut
|
||||
isBackorder
|
||||
shop {
|
||||
currency {
|
||||
code
|
||||
}
|
||||
}
|
||||
pricing {
|
||||
currency {
|
||||
code
|
||||
}
|
||||
displayPrice
|
||||
minPrice
|
||||
maxPrice
|
||||
}
|
||||
primaryImage {
|
||||
URLs {
|
||||
thumbnail
|
||||
small
|
||||
medium
|
||||
large
|
||||
original
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}`
|
||||
|
||||
export const catalogItemsFragment = `
|
||||
catalogItems(
|
||||
first: $first
|
||||
sortBy: $sortBy
|
||||
tagIds: $tagIds
|
||||
shopIds: $shopIds
|
||||
) {
|
||||
${catalogItemsConnection}
|
||||
}
|
||||
`
|
||||
|
||||
const catalogItemsQuery = /* GraphQL */ `
|
||||
query catalogItems(
|
||||
$first: ConnectionLimitInt = 250
|
||||
$sortBy: CatalogItemSortByField = updatedAt
|
||||
$tagIds: [ID]
|
||||
$shopIds: [ID]!
|
||||
) {
|
||||
${catalogItemsFragment}
|
||||
}
|
||||
`
|
||||
export default catalogItemsQuery
|
@ -0,0 +1,14 @@
|
||||
const getTagsQuery = /* GraphQL */ `
|
||||
query getTags($first: ConnectionLimitInt!, $shopId: ID!) {
|
||||
tags(first: $first, shopId: $shopId) {
|
||||
edges {
|
||||
node {
|
||||
_id
|
||||
displayTitle
|
||||
slug
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
export default getTagsQuery
|
@ -0,0 +1,14 @@
|
||||
export const getAllPagesQuery = /* GraphQL */ `
|
||||
query getAllPages($first: Int = 250) {
|
||||
pages(first: $first) {
|
||||
edges {
|
||||
node {
|
||||
id
|
||||
title
|
||||
handle
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
export default getAllPagesQuery
|
@ -0,0 +1,17 @@
|
||||
const getAllProductVendors = /* GraphQL */ `
|
||||
query getAllProductVendors($first: Int = 250, $cursor: String) {
|
||||
products(first: $first, after: $cursor) {
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
hasPreviousPage
|
||||
}
|
||||
edges {
|
||||
node {
|
||||
vendor
|
||||
}
|
||||
cursor
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
export default getAllProductVendors
|
@ -0,0 +1,25 @@
|
||||
const getAllProductsPathsQuery = /* GraphQL */ `
|
||||
query catalogItems(
|
||||
$first: ConnectionLimitInt = 250
|
||||
$sortBy: CatalogItemSortByField = updatedAt
|
||||
$shopIds: [ID]!
|
||||
) {
|
||||
catalogItems(first: $first, sortBy: $sortBy, shopIds: $shopIds) {
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
hasPreviousPage
|
||||
}
|
||||
edges {
|
||||
node {
|
||||
... on CatalogItemProduct {
|
||||
product {
|
||||
slug
|
||||
}
|
||||
}
|
||||
}
|
||||
cursor
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
export default getAllProductsPathsQuery
|
@ -0,0 +1,11 @@
|
||||
import { cartQueryFragment } from '../queries/get-checkout-query'
|
||||
|
||||
export const getAnomymousCart = `
|
||||
query anonymousCartByCartIdQuery($cartId: ID!, $cartToken: String!, $itemsAfterCursor: ConnectionCursor) {
|
||||
cart: anonymousCartByCartId(cartId: $cartId, cartToken: $cartToken) {
|
||||
${cartQueryFragment}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export default getAnomymousCart
|
241
framework/reactioncommerce/utils/queries/get-checkout-query.ts
Normal file
241
framework/reactioncommerce/utils/queries/get-checkout-query.ts
Normal file
@ -0,0 +1,241 @@
|
||||
export const cartCommon = `
|
||||
_id
|
||||
createdAt
|
||||
account {
|
||||
_id
|
||||
emailRecords {
|
||||
address
|
||||
}
|
||||
}
|
||||
shop {
|
||||
_id
|
||||
currency {
|
||||
code
|
||||
}
|
||||
}
|
||||
email
|
||||
updatedAt
|
||||
expiresAt
|
||||
checkout {
|
||||
fulfillmentGroups {
|
||||
_id
|
||||
type
|
||||
data {
|
||||
shippingAddress {
|
||||
address1
|
||||
address2
|
||||
city
|
||||
company
|
||||
country
|
||||
fullName
|
||||
isBillingDefault
|
||||
isCommercial
|
||||
isShippingDefault
|
||||
phone
|
||||
postal
|
||||
region
|
||||
}
|
||||
}
|
||||
availableFulfillmentOptions {
|
||||
price {
|
||||
amount
|
||||
displayAmount
|
||||
}
|
||||
fulfillmentMethod {
|
||||
_id
|
||||
name
|
||||
displayName
|
||||
}
|
||||
}
|
||||
selectedFulfillmentOption {
|
||||
fulfillmentMethod {
|
||||
_id
|
||||
name
|
||||
displayName
|
||||
}
|
||||
price {
|
||||
amount
|
||||
displayAmount
|
||||
}
|
||||
handlingPrice {
|
||||
amount
|
||||
displayAmount
|
||||
}
|
||||
}
|
||||
shop {
|
||||
_id
|
||||
}
|
||||
shippingAddress {
|
||||
address1
|
||||
address2
|
||||
city
|
||||
company
|
||||
country
|
||||
fullName
|
||||
isBillingDefault
|
||||
isCommercial
|
||||
isShippingDefault
|
||||
phone
|
||||
postal
|
||||
region
|
||||
}
|
||||
}
|
||||
summary {
|
||||
fulfillmentTotal {
|
||||
displayAmount
|
||||
}
|
||||
itemTotal {
|
||||
amount
|
||||
displayAmount
|
||||
}
|
||||
surchargeTotal {
|
||||
amount
|
||||
displayAmount
|
||||
}
|
||||
taxTotal {
|
||||
amount
|
||||
displayAmount
|
||||
}
|
||||
total {
|
||||
amount
|
||||
currency {
|
||||
code
|
||||
}
|
||||
displayAmount
|
||||
}
|
||||
}
|
||||
}
|
||||
totalItemQuantity
|
||||
`
|
||||
|
||||
const cartItemConnectionFragment = `
|
||||
pageInfo {
|
||||
hasNextPage
|
||||
endCursor
|
||||
}
|
||||
edges {
|
||||
node {
|
||||
_id
|
||||
productConfiguration {
|
||||
productId
|
||||
productVariantId
|
||||
}
|
||||
addedAt
|
||||
attributes {
|
||||
label
|
||||
value
|
||||
}
|
||||
createdAt
|
||||
isBackorder
|
||||
isLowQuantity
|
||||
isSoldOut
|
||||
imageURLs {
|
||||
large
|
||||
small
|
||||
original
|
||||
medium
|
||||
thumbnail
|
||||
}
|
||||
metafields {
|
||||
value
|
||||
key
|
||||
}
|
||||
parcel {
|
||||
length
|
||||
width
|
||||
weight
|
||||
height
|
||||
}
|
||||
price {
|
||||
amount
|
||||
displayAmount
|
||||
currency {
|
||||
code
|
||||
}
|
||||
}
|
||||
priceWhenAdded {
|
||||
amount
|
||||
displayAmount
|
||||
currency {
|
||||
code
|
||||
}
|
||||
}
|
||||
productSlug
|
||||
productType
|
||||
quantity
|
||||
shop {
|
||||
_id
|
||||
}
|
||||
subtotal {
|
||||
displayAmount
|
||||
}
|
||||
title
|
||||
productTags {
|
||||
nodes {
|
||||
name
|
||||
}
|
||||
}
|
||||
productVendor
|
||||
variantTitle
|
||||
optionTitle
|
||||
updatedAt
|
||||
inventoryAvailableToSell
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export const cartPayloadFragment = `
|
||||
${cartCommon}
|
||||
items {
|
||||
${cartItemConnectionFragment}
|
||||
}
|
||||
`
|
||||
|
||||
export const incorrectPriceFailureDetailsFragment = `
|
||||
currentPrice {
|
||||
amount
|
||||
currency {
|
||||
code
|
||||
}
|
||||
displayAmount
|
||||
}
|
||||
productConfiguration {
|
||||
productId
|
||||
productVariantId
|
||||
}
|
||||
providedPrice {
|
||||
amount
|
||||
currency {
|
||||
code
|
||||
}
|
||||
displayAmount
|
||||
}
|
||||
`
|
||||
|
||||
export const minOrderQuantityFailureDetailsFragment = `
|
||||
minOrderQuantity
|
||||
productConfiguration {
|
||||
productId
|
||||
productVariantId
|
||||
}
|
||||
quantity
|
||||
`
|
||||
|
||||
const getCheckoutQuery = /* GraphQL */ `
|
||||
query($checkoutId: ID!) {
|
||||
node(id: $checkoutId) {
|
||||
... on Checkout {
|
||||
${cartCommon}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export const cartQueryFragment = `
|
||||
${cartCommon}
|
||||
items(first: 20, after: $itemsAfterCursor) {
|
||||
${cartItemConnectionFragment}
|
||||
}
|
||||
`
|
||||
|
||||
export default getCheckoutQuery
|
@ -0,0 +1,24 @@
|
||||
import { catalogItemsConnection } from './catalog-items-query'
|
||||
|
||||
const getCollectionProductsQuery = /* GraphQL */ `
|
||||
query getProductsFromCollection(
|
||||
$categoryId: ID!
|
||||
$first: Int = 250
|
||||
$sortKey: ProductCollectionSortKeys = RELEVANCE
|
||||
$reverse: Boolean = false
|
||||
) {
|
||||
node(id: $categoryId) {
|
||||
id
|
||||
... on Collection {
|
||||
products(
|
||||
first: $first
|
||||
sortKey: $sortKey
|
||||
reverse: $reverse
|
||||
) {
|
||||
${catalogItemsConnection}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
export default getCollectionProductsQuery
|
@ -0,0 +1,8 @@
|
||||
export const getCustomerQuery = /* GraphQL */ `
|
||||
query getCustomerId($customerAccessToken: String!) {
|
||||
customer(customerAccessToken: $customerAccessToken) {
|
||||
id
|
||||
}
|
||||
}
|
||||
`
|
||||
export default getCustomerQuery
|
@ -0,0 +1,16 @@
|
||||
export const getCustomerQuery = /* GraphQL */ `
|
||||
query getCustomer($customerAccessToken: String!) {
|
||||
customer(customerAccessToken: $customerAccessToken) {
|
||||
id
|
||||
firstName
|
||||
lastName
|
||||
displayName
|
||||
email
|
||||
phone
|
||||
tags
|
||||
acceptsMarketing
|
||||
createdAt
|
||||
}
|
||||
}
|
||||
`
|
||||
export default getCustomerQuery
|
14
framework/reactioncommerce/utils/queries/get-page-query.ts
Normal file
14
framework/reactioncommerce/utils/queries/get-page-query.ts
Normal file
@ -0,0 +1,14 @@
|
||||
export const getPageQuery = /* GraphQL */ `
|
||||
query($id: ID!) {
|
||||
node(id: $id) {
|
||||
id
|
||||
... on Page {
|
||||
title
|
||||
handle
|
||||
body
|
||||
bodySummary
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
export default getPageQuery
|
181
framework/reactioncommerce/utils/queries/get-product-query.ts
Normal file
181
framework/reactioncommerce/utils/queries/get-product-query.ts
Normal file
@ -0,0 +1,181 @@
|
||||
const getProductQuery = /* GraphQL */ `
|
||||
query getProductBySlug($slug: String!) {
|
||||
catalogItemProduct(slugOrId: $slug) {
|
||||
product {
|
||||
_id
|
||||
productId
|
||||
title
|
||||
slug
|
||||
description
|
||||
vendor
|
||||
isLowQuantity
|
||||
isSoldOut
|
||||
isBackorder
|
||||
metafields {
|
||||
description
|
||||
key
|
||||
namespace
|
||||
scope
|
||||
value
|
||||
valueType
|
||||
}
|
||||
pricing {
|
||||
currency {
|
||||
code
|
||||
}
|
||||
displayPrice
|
||||
minPrice
|
||||
maxPrice
|
||||
}
|
||||
shop {
|
||||
currency {
|
||||
code
|
||||
}
|
||||
}
|
||||
primaryImage {
|
||||
URLs {
|
||||
large
|
||||
medium
|
||||
original
|
||||
small
|
||||
thumbnail
|
||||
}
|
||||
priority
|
||||
productId
|
||||
variantId
|
||||
}
|
||||
media {
|
||||
priority
|
||||
productId
|
||||
variantId
|
||||
URLs {
|
||||
thumbnail
|
||||
small
|
||||
medium
|
||||
large
|
||||
original
|
||||
}
|
||||
}
|
||||
tags {
|
||||
nodes {
|
||||
name
|
||||
slug
|
||||
position
|
||||
}
|
||||
}
|
||||
variants {
|
||||
_id
|
||||
variantId
|
||||
attributeLabel
|
||||
title
|
||||
optionTitle
|
||||
index
|
||||
pricing {
|
||||
compareAtPrice {
|
||||
displayAmount
|
||||
}
|
||||
price
|
||||
currency {
|
||||
code
|
||||
}
|
||||
displayPrice
|
||||
}
|
||||
canBackorder
|
||||
inventoryAvailableToSell
|
||||
isBackorder
|
||||
isSoldOut
|
||||
isLowQuantity
|
||||
options {
|
||||
_id
|
||||
variantId
|
||||
attributeLabel
|
||||
title
|
||||
index
|
||||
pricing {
|
||||
compareAtPrice {
|
||||
displayAmount
|
||||
}
|
||||
price
|
||||
currency {
|
||||
code
|
||||
}
|
||||
displayPrice
|
||||
}
|
||||
optionTitle
|
||||
canBackorder
|
||||
inventoryAvailableToSell
|
||||
isBackorder
|
||||
isSoldOut
|
||||
isLowQuantity
|
||||
media {
|
||||
priority
|
||||
productId
|
||||
variantId
|
||||
URLs {
|
||||
thumbnail
|
||||
small
|
||||
medium
|
||||
large
|
||||
original
|
||||
}
|
||||
}
|
||||
metafields {
|
||||
description
|
||||
key
|
||||
namespace
|
||||
scope
|
||||
value
|
||||
valueType
|
||||
}
|
||||
primaryImage {
|
||||
URLs {
|
||||
large
|
||||
medium
|
||||
original
|
||||
small
|
||||
thumbnail
|
||||
}
|
||||
priority
|
||||
productId
|
||||
variantId
|
||||
}
|
||||
}
|
||||
media {
|
||||
priority
|
||||
productId
|
||||
variantId
|
||||
URLs {
|
||||
thumbnail
|
||||
small
|
||||
medium
|
||||
large
|
||||
original
|
||||
}
|
||||
}
|
||||
metafields {
|
||||
description
|
||||
key
|
||||
namespace
|
||||
scope
|
||||
value
|
||||
valueType
|
||||
}
|
||||
primaryImage {
|
||||
URLs {
|
||||
large
|
||||
medium
|
||||
original
|
||||
small
|
||||
thumbnail
|
||||
}
|
||||
priority
|
||||
productId
|
||||
variantId
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
export default getProductQuery
|
10
framework/reactioncommerce/utils/queries/index.ts
Normal file
10
framework/reactioncommerce/utils/queries/index.ts
Normal file
@ -0,0 +1,10 @@
|
||||
export { default as getTagsQuery } from './get-all-collections-query'
|
||||
export { default as getProductQuery } from './get-product-query'
|
||||
export { default as catalogItemsQuery } from './catalog-items-query'
|
||||
export { default as getAllProductsPathtsQuery } from './get-all-products-paths-query'
|
||||
export { default as getAllProductVendors } from './get-all-product-vendors-query'
|
||||
export { default as getCollectionProductsQuery } from './get-collection-products-query'
|
||||
export { default as getCheckoutQuery } from './get-checkout-query'
|
||||
export { default as getAllPagesQuery } from './get-all-pages-query'
|
||||
export { default as getPageQuery } from './get-page-query'
|
||||
export { default as getCustomerQuery } from './get-customer-query'
|
@ -3,6 +3,7 @@ const withCommerceConfig = require('./framework/commerce/with-config')
|
||||
|
||||
const isBC = commerce.provider === 'bigcommerce'
|
||||
const isShopify = commerce.provider === 'shopify'
|
||||
const isRC = commerce.provider === 'reactioncommerce'
|
||||
|
||||
module.exports = withCommerceConfig({
|
||||
commerce,
|
||||
@ -12,7 +13,7 @@ module.exports = withCommerceConfig({
|
||||
},
|
||||
rewrites() {
|
||||
return [
|
||||
(isBC || isShopify) && {
|
||||
(isBC || isShopify || isRC) && {
|
||||
source: '/checkout',
|
||||
destination: '/api/bigcommerce/checkout',
|
||||
},
|
||||
|
@ -2,7 +2,7 @@
|
||||
"name": "nextjs-commerce",
|
||||
"version": "1.0.0",
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"dev": "next dev -p 8080",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"analyze": "BUNDLE_ANALYZE=both yarn build",
|
||||
|
3
pages/api/reactioncommerce/cart.ts
Normal file
3
pages/api/reactioncommerce/cart.ts
Normal file
@ -0,0 +1,3 @@
|
||||
import cartApi from '@framework/api/cart'
|
||||
|
||||
export default cartApi()
|
@ -46,6 +46,7 @@ export async function getStaticProps({
|
||||
pages,
|
||||
categories,
|
||||
brands,
|
||||
shopId: config?.shopId,
|
||||
},
|
||||
}
|
||||
}
|
||||
@ -53,6 +54,7 @@ export async function getStaticProps({
|
||||
export default function Search({
|
||||
categories,
|
||||
brands,
|
||||
shopId,
|
||||
}: InferGetStaticPropsType<typeof getStaticProps>) {
|
||||
const [activeFilter, setActiveFilter] = useState('')
|
||||
const [toggleFilter, setToggleFilter] = useState(false)
|
||||
@ -80,6 +82,7 @@ export default function Search({
|
||||
// TODO: Shopify - Fix this type
|
||||
brandId: (activeBrand as any)?.entityId,
|
||||
sort: typeof sort === 'string' ? sort : '',
|
||||
shopId,
|
||||
})
|
||||
|
||||
const handleClick = (event: any, filter: string) => {
|
||||
|
@ -22,8 +22,8 @@
|
||||
"@components/*": ["components/*"],
|
||||
"@commerce": ["framework/commerce"],
|
||||
"@commerce/*": ["framework/commerce/*"],
|
||||
"@framework": ["framework/bigcommerce"],
|
||||
"@framework/*": ["framework/bigcommerce/*"]
|
||||
"@framework": ["framework/reactioncommerce"],
|
||||
"@framework/*": ["framework/reactioncommerce/*"]
|
||||
}
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.d.ts", "**/*.ts", "**/*.tsx", "**/*.js"],
|
||||
|
Loading…
x
Reference in New Issue
Block a user