From 18936b7544f39eed8e86d2bd3fd9a3a345144c78 Mon Sep 17 00:00:00 2001 From: Greg Hoskin Date: Thu, 1 Apr 2021 16:32:12 -0600 Subject: [PATCH] update get product hook --- framework/swell/api/utils/fetch-swell-api.ts | 8 +- framework/swell/cart/use-cart.tsx | 64 ++++--------- framework/swell/cart/utils/checkout-create.ts | 27 +++--- framework/swell/cart/utils/fetcher.ts | 32 ++++--- framework/swell/fetcher.ts | 2 + framework/swell/product/get-product.ts | 6 +- framework/swell/product/use-search.tsx | 4 +- framework/swell/utils/normalize.ts | 91 +++++++++---------- 8 files changed, 103 insertions(+), 131 deletions(-) diff --git a/framework/swell/api/utils/fetch-swell-api.ts b/framework/swell/api/utils/fetch-swell-api.ts index c4c9472cf..805aa46e8 100644 --- a/framework/swell/api/utils/fetch-swell-api.ts +++ b/framework/swell/api/utils/fetch-swell-api.ts @@ -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 } diff --git a/framework/swell/cart/use-cart.tsx b/framework/swell/cart/use-cart.tsx index a1a303210..c9589f484 100644 --- a/framework/swell/cart/use-cart.tsx +++ b/framework/swell/cart/use-cart.tsx @@ -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 +export default useCart as UseCart -export const handler: SWRHook< - Cart | null, - {}, - FetchCartInput, - { isEmpty?: boolean } -> = { +export const handler: SWRHook = { 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({ + ...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] - ) }, } diff --git a/framework/swell/cart/utils/checkout-create.ts b/framework/swell/cart/utils/checkout-create.ts index e950cc7e4..73109baad 100644 --- a/framework/swell/cart/utils/checkout-create.ts +++ b/framework/swell/cart/utils/checkout-create.ts @@ -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 diff --git a/framework/swell/cart/utils/fetcher.ts b/framework/swell/cart/utils/fetcher.ts index 6afb55f18..2e7ae15d3 100644 --- a/framework/swell/cart/utils/fetcher.ts +++ b/framework/swell/cart/utils/fetcher.ts @@ -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 = 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 diff --git a/framework/swell/fetcher.ts b/framework/swell/fetcher.ts index e52d8fd54..4c65b91d2 100644 --- a/framework/swell/fetcher.ts +++ b/framework/swell/fetcher.ts @@ -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) } diff --git a/framework/swell/product/get-product.ts b/framework/swell/product/get-product.ts index cfac8e984..c06617221 100644 --- a/framework/swell/product/get-product.ts +++ b/framework/swell/product/get-product.ts @@ -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, diff --git a/framework/swell/product/use-search.tsx b/framework/swell/product/use-search.tsx index a00e39dc9..4e55da22a 100644 --- a/framework/swell/product/use-search.tsx +++ b/framework/swell/product/use-search.tsx @@ -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)) diff --git a/framework/swell/utils/normalize.ts b/framework/swell/utils/normalize.ts index 6dbb6d708..bbb974c5e 100644 --- a/framework/swell/utils/normalize.ts +++ b/framework/swell/utils/normalize.ts @@ -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, }, ], }