4
0
forked from crowetic/commerce

update get product hook

This commit is contained in:
Greg Hoskin 2021-04-01 16:32:12 -06:00
parent 1ebf458fb2
commit 18936b7544
8 changed files with 103 additions and 131 deletions

View File

@ -1,8 +1,12 @@
import { swellConfig } from '../../index'
const fetchSwellApi = async (query: string, method: string) => {
const fetchSwellApi = async (
query: string,
method: string,
variables: object | string
) => {
const { swell } = swellConfig
const res = await swell[query][method]()
const res = await swell[query][method](variables)
return res
}

View File

@ -1,60 +1,28 @@
import { useMemo } from 'react'
import useCommerceCart, {
FetchCartInput,
UseCart,
} from '@commerce/cart/use-cart'
import { Cart } from '../types'
import useCart, { UseCart } from '@commerce/cart/use-cart'
import { Customer } from '@commerce/types'
import { SWRHook } from '@commerce/utils/types'
import { checkoutCreate, checkoutToCart } from './utils'
import getCheckoutQuery from '../utils/queries/get-checkout-query'
import { normalizeCart } from '../utils/normalize'
// import { getCustomerQuery, getCustomerToken } from '../utils'
export default useCommerceCart as UseCart<typeof handler>
export default useCart as UseCart<typeof handler>
export const handler: SWRHook<
Cart | null,
{},
FetchCartInput,
{ isEmpty?: boolean }
> = {
export const handler: SWRHook<Customer | null> = {
fetchOptions: {
query: 'cart',
method: 'get',
},
async fetcher({ input: { cartId: checkoutId }, options, 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)
async fetcher({ options, fetch }) {
const data = await fetch<any | null>({
...options,
})
return data ? normalizeCart(data) : null
},
useHook: ({ useData }) => (input) => {
const response = useData({
swrOptions: { revalidateOnFocus: false, ...input?.swrOptions },
return useData({
swrOptions: {
revalidateOnFocus: false,
...input?.swrOptions,
},
})
return useMemo(
() =>
Object.create(response, {
isEmpty: {
get() {
return (response.data?.lineItems.length ?? 0) <= 0
},
enumerable: true,
},
}),
[response]
)
},
}

View File

@ -4,26 +4,27 @@ import {
SHOPIFY_COOKIE_EXPIRE,
} from '../../const'
import checkoutCreateMutation from '../../utils/mutations/checkout-create'
// import checkoutCreateMutation from '../../utils/mutations/checkout-create'
import Cookies from 'js-cookie'
export const checkoutCreate = async (fetch: any) => {
const data = await fetch({
query: checkoutCreateMutation,
const cart = await fetch({
query: 'cart',
method: 'get',
})
const checkout = data.checkoutCreate?.checkout
const checkoutId = checkout?.id
// const checkout = data.checkoutCreate?.checkout
const checkoutId = cart?.id
if (checkoutId) {
const options = {
expires: SHOPIFY_COOKIE_EXPIRE,
}
Cookies.set(SHOPIFY_CHECKOUT_ID_COOKIE, checkoutId, options)
Cookies.set(SHOPIFY_CHECKOUT_URL_COOKIE, checkout?.webUrl, options)
}
// if (checkoutId) {
// const options = {
// expires: SHOPIFY_COOKIE_EXPIRE,
// }
// Cookies.set(SHOPIFY_CHECKOUT_ID_COOKIE, checkoutId, options)
// Cookies.set(SHOPIFY_CHECKOUT_URL_COOKIE, checkout?.webUrl, options)
// }
return checkout
return cart
}
export default checkoutCreate

View File

@ -1,31 +1,33 @@
import { HookFetcherFn } from '@commerce/utils/types'
import { Cart } from '@commerce/types'
import { checkoutCreate, checkoutToCart } from '.'
// import { checkoutCreate, checkoutToCart } from '.'
import { FetchCartInput } from '@commerce/cart/use-cart'
import { data } from 'autoprefixer'
import { normalizeCart } from '../../utils'
const fetcher: HookFetcherFn<Cart | null, FetchCartInput> = async ({
options,
input: { cartId: checkoutId },
// input: { cartId: checkoutId },
fetch,
}) => {
let checkout
if (checkoutId) {
const data = await fetch({
...options,
variables: {
checkoutId,
},
})
checkout = data.node
}
// if (checkoutId) {
const data = await fetch({
query: 'cart',
method: 'get',
// variables: { category: categoryId },
})
// checkout = data.node
// }
if (checkout?.completedAt || !checkoutId) {
checkout = await checkoutCreate(fetch)
}
// if (checkout?.completedAt || !checkoutId) {
// checkout = await checkoutCreate(fetch)
// }
// TODO: Fix this type
return checkoutToCart({ checkout } as any)
// return checkoutToCart({ checkout } as any)
return normalizeCart(data)
}
export default fetcher

View File

@ -8,9 +8,11 @@ const fetcher: Fetcher = async ({ method = 'get', variables, query }) => {
if (Array.isArray(variables)) {
const arg1 = variables[0]
const arg2 = variables[1]
// console.log('fetcher', query, method, variables);
const response = await swell[query][method](arg1, arg2)
return handleFetchResponse(response)
} else {
// console.log('fetcher', query, method, variables);
const response = await swell[query][method](variables)
return handleFetchResponse(response)
}

View File

@ -18,11 +18,7 @@ const getProduct = async (options: {
let { config, variables } = options ?? {}
config = getConfig(config)
const { data }: GraphQLFetcherResult = await config.fetch(getProductQuery, {
variables,
})
const { productByHandle: product } = data
const product = await config.fetchSwell('products', 'get', variables.slug)
return {
product: product ? normalizeProduct(product) : null,

View File

@ -32,8 +32,8 @@ export const handler: SWRHook<
const { results, count: found } = await fetch({
query: 'products',
method: 'get',
// variables: { categoryId },
method: 'list',
variables: { category: categoryId },
})
const products = results.map((product) => normalizeProduct(product))

View File

@ -47,31 +47,28 @@ const normalizeProductOption = ({
}
const normalizeProductImages = (images) =>
images?.map(({ file, ...rest }) => ({
images?.map(({ file, id }) => ({
url: file.url,
...rest,
id,
}))
const normalizeProductVariants = ({ edges }: ProductVariantConnection) => {
return edges?.map(
({
node: { id, selectedOptions, sku, title, priceV2, compareAtPriceV2 },
}) => ({
id,
name: title,
sku: sku ?? id,
price: +priceV2.amount,
listPrice: +compareAtPriceV2?.amount,
requiresShipping: true,
options: selectedOptions.map(({ name, value }: SelectedOption) =>
normalizeProductOption({
id,
name,
values: [value],
})
),
})
)
const normalizeProductVariants = (variants) => {
// console.log('variant', variants);
return variants?.map(({ id, name, values, price, stock_status }) => ({
id,
name,
sku: sku ?? id,
price,
listPrice: price,
// requiresShipping: true,
options: values.map(({ name, value }: SelectedOption) =>
normalizeProductOption({
id,
name,
values: [value],
})
),
}))
}
export function normalizeProduct(productNode: SwellProduct): Product {
@ -91,13 +88,13 @@ export function normalizeProduct(productNode: SwellProduct): Product {
const product = {
id,
name,
vendor,
vendor: 'our brands',
description,
path: `/${slug}`,
slug,
price,
images: normalizeProductImages(images),
variants: variants ? normalizeProductVariants(variants) : [],
variants: [], //variants ? normalizeProductVariants(options) : [],
options: options ? options.map((o) => normalizeProductOption(o)) : [],
...rest,
}
@ -105,21 +102,19 @@ export function normalizeProduct(productNode: SwellProduct): Product {
return product
}
export function normalizeCart(checkout: Checkout): Cart {
export function normalizeCart(cart: Checkout): Cart {
return {
id: checkout.id,
customerId: '',
id: cart.id,
customerId: cart.account_id,
email: '',
createdAt: checkout.createdAt,
currency: {
code: checkout.totalPriceV2?.currencyCode,
},
taxesIncluded: checkout.taxesIncluded,
lineItems: checkout.lineItems?.edges.map(normalizeLineItem),
lineItemsSubtotalPrice: +checkout.subtotalPriceV2?.amount,
subtotalPrice: +checkout.subtotalPriceV2?.amount,
totalPrice: checkout.totalPriceV2?.amount,
discounts: [],
createdAt: cart.date_created,
currency: cart.currency,
taxesIncluded: cart.tax_included_total,
lineItems: cart.items?.map(normalizeLineItem),
lineItemsSubtotalPrice: +cart.sub_total,
subtotalPrice: +cart.sub_total,
totalPrice: cart.grand_total,
discounts: cart.discounts,
}
}
@ -133,30 +128,34 @@ export function normalizeCustomer(customer: SwellCustomer): Customer {
}
function normalizeLineItem({
node: { id, title, variant, quantity },
id,
product,
price,
variant,
quantity,
}: CheckoutLineItemEdge): LineItem {
return {
id,
variantId: String(variant?.id),
productId: String(variant?.id),
name: `${title}`,
productId: String(product?.id),
name: product.name,
quantity,
variant: {
id: String(variant?.id),
sku: variant?.sku ?? '',
name: variant?.title!,
name: variant?.name!,
image: {
url: variant?.image?.originalSrc,
url: product?.images[0].file.url,
},
requiresShipping: variant?.requiresShipping ?? false,
price: variant?.priceV2?.amount,
listPrice: variant?.compareAtPriceV2?.amount,
requiresShipping: false,
price: price,
listPrice: price,
},
path: '',
discounts: [],
options: [
{
value: variant?.title,
value: variant?.name,
},
],
}