4
0
forked from crowetic/commerce

handle empty cart, variants, options, errors

This commit is contained in:
Greg Hoskin 2021-04-30 18:35:19 -05:00
parent b83753f0b9
commit ffbcce2a9e
8 changed files with 33 additions and 75 deletions

View File

@ -1,21 +0,0 @@
import Client from 'shopify-buy'
import { SwellConfig } from '../index'
type Options = {
config: SwellConfig
}
const getAllCollections = async (options: Options) => {
const { config } = options
const client = Client.buildClient({
storefrontAccessToken: config.apiToken,
domain: config.commerceUrl,
})
const res = await client.collection.fetchAllWithProducts()
return JSON.parse(JSON.stringify(res))
}
export default getAllCollections

View File

@ -1,5 +1,5 @@
import { ProductEdge } from '../../schema'
import { SwellConfig } from '..' import { SwellConfig } from '..'
import { SwellProduct } from '../../types'
const fetchAllProducts = async ({ const fetchAllProducts = async ({
config, config,
@ -7,35 +7,17 @@ const fetchAllProducts = async ({
method, method,
variables, variables,
acc = [], acc = [],
cursor,
}: { }: {
config: SwellConfig config: SwellConfig
query: string query: string
acc?: ProductEdge[] method: string
acc?: SwellProduct[]
variables?: any variables?: any
cursor?: string cursor?: string
}): Promise<ProductEdge[]> => { }): Promise<SwellProduct[]> => {
// const response = await config.fetch(query, { const response = await config.fetchSwell(query, method, variables)
// variables: { ...variables, cursor },
// })
const response = await config.fetchSwell('products', 'list', [{ limit: 100 }])
const edges: ProductEdge[] = response.results ?? [] acc = acc.concat(response.results)
const hasNextPage = response.results.length < response.count
acc = acc.concat(edges)
if (hasNextPage) {
const cursor = edges.pop()?.cursor
if (cursor) {
return fetchAllProducts({
config,
query,
variables,
acc,
cursor,
})
}
}
return acc return acc
} }

View File

@ -8,6 +8,14 @@ export const checkoutCreate = async (fetch: any) => {
method: 'get', method: 'get',
}) })
if (!cart) {
const cart = await fetch({
query: 'cart',
method: 'setItems',
variables: [[]],
})
}
const checkoutUrl = cart?.checkout_url const checkoutUrl = cart?.checkout_url
if (checkoutUrl) { if (checkoutUrl) {

View File

@ -1,7 +1,5 @@
import { Product } from '@commerce/types'
import { getConfig, SwellConfig } from '../api' import { getConfig, SwellConfig } from '../api'
import fetchAllProducts from '../api/utils/fetch-all-products' import fetchAllProducts from '../api/utils/fetch-all-products'
import { ProductEdge } from '../schema'
type ProductPath = { type ProductPath = {
path: string path: string
@ -20,7 +18,7 @@ const getAllProductPaths = async (options?: {
config?: SwellConfig config?: SwellConfig
preview?: boolean preview?: boolean
}): Promise<ReturnType> => { }): Promise<ReturnType> => {
let { config, variables = { limit: 100 } } = options ?? {} let { config, variables = [{ limit: 100 }] } = options ?? {}
config = getConfig(config) config = getConfig(config)
const products = await fetchAllProducts({ const products = await fetchAllProducts({

View File

@ -19,11 +19,11 @@ const getProduct = async (options: {
config = getConfig(config) config = getConfig(config)
const product = await config.fetchSwell('products', 'get', [variables.slug]) const product = await config.fetchSwell('products', 'get', [variables.slug])
if (product.variants) { if (product && product.variants) {
product.variants = product.variants?.results product.variants = product.variants?.results
} }
return { return {
product: normalizeProduct(product), product: product ? normalizeProduct(product) : null,
} }
} }

View File

@ -13,7 +13,7 @@ export type Brands = BrandEdge[]
const getVendors = async (config: SwellConfig) => { const getVendors = async (config: SwellConfig) => {
const vendors: [string] = const vendors: [string] =
(await config.fetchSwell('attributes', 'get', ['brand'])).values ?? [] (await config.fetchSwell('attributes', 'get', ['brand']))?.values ?? []
return [...new Set(vendors)].map((v) => ({ return [...new Set(vendors)].map((v) => ({
node: { node: {

View File

@ -1,28 +1,19 @@
import { FetcherError } from '@commerce/utils/errors' import { CommerceError } from '@commerce/utils/errors'
export function getError(errors: any[], status: number) { type SwellFetchResponse = {
errors = errors ?? [{ message: 'Failed to fetch Swell API' }] error: {
return new FetcherError({ errors, status }) message: string
code?: string
}
} }
export async function getAsyncError(res: Response) { const handleFetchResponse = async (res: SwellFetchResponse) => {
const data = await res.json() if (res) {
return getError(data.errors, res.status) if (res.error) {
} throw new CommerceError(res.error)
}
const handleFetchResponse = async (res: Response) => { return res
// if (res.ok) { }
// const { data, errors } = await res.json()
// if (errors && errors.length) {
// throw getError(errors, res.status)
// }
// return data
// }
if (res) return res
throw await getAsyncError(res)
} }
export default handleFetchResponse export default handleFetchResponse

View File

@ -76,7 +76,7 @@ const normalizeProductVariants = (
productOptions: normalizedProductOption[] productOptions: normalizedProductOption[]
) => { ) => {
return variants?.map( return variants?.map(
({ id, name, price, option_value_ids: optionValueIds }) => { ({ id, name, price, option_value_ids: optionValueIds = [] }) => {
const values = name const values = name
.split(',') .split(',')
.map((i) => ({ name: i.trim(), label: i.trim() })) .map((i) => ({ name: i.trim(), label: i.trim() }))
@ -167,7 +167,7 @@ export function normalizeCart({
createdAt: date_created, createdAt: date_created,
currency: { code: currency }, currency: { code: currency },
taxesIncluded: tax_included_total > 0, taxesIncluded: tax_included_total > 0,
lineItems: items?.map(normalizeLineItem), lineItems: items?.map(normalizeLineItem) ?? [],
lineItemsSubtotalPrice: +sub_total, lineItemsSubtotalPrice: +sub_total,
subtotalPrice: +sub_total, subtotalPrice: +sub_total,
totalPrice: grand_total, totalPrice: grand_total,