4
0
forked from crowetic/commerce

enable add and remove items (update) from cart. Update Search

This commit is contained in:
Greg Hoskin 2021-04-04 16:16:27 -06:00
parent 18936b7544
commit d0a04a8fe9
7 changed files with 41 additions and 50 deletions

View File

@ -23,11 +23,7 @@ export const handler: MutationHook<Cart, {}, CartItemBody> = {
message: 'The item quantity has to be a valid integer greater than 0', message: 'The item quantity has to be a valid integer greater than 0',
}) })
} }
const response = await fetch<Mutation, MutationCheckoutLineItemsAddArgs>({
const { checkoutLineItemsAdd } = await fetch<
Mutation,
MutationCheckoutLineItemsAddArgs
>({
...options, ...options,
variables: { variables: {
checkoutId: getCheckoutId(), checkoutId: getCheckoutId(),

View File

@ -1,12 +1,12 @@
import useCart, { UseCart } from '@commerce/cart/use-cart' import useCart, { UseCart } from '@commerce/cart/use-cart'
import { Customer } from '@commerce/types' import { Cart } from '@commerce/types'
import { SWRHook } from '@commerce/utils/types' import { SWRHook } from '@commerce/utils/types'
import { normalizeCart } from '../utils/normalize' import { normalizeCart } from '../utils/normalize'
// import { getCustomerQuery, getCustomerToken } from '../utils' // import { getCustomerQuery, getCustomerToken } from '../utils'
export default useCart as UseCart<typeof handler> export default useCart as UseCart<typeof handler>
export const handler: SWRHook<Customer | null> = { export const handler: SWRHook<Cart | null> = {
fetchOptions: { fetchOptions: {
query: 'cart', query: 'cart',
method: 'get', method: 'get',

View File

@ -14,7 +14,6 @@ import useCart from './use-cart'
import { handler as removeItemHandler } from './use-remove-item' import { handler as removeItemHandler } from './use-remove-item'
import type { Cart, LineItem, UpdateCartItemBody } from '../types' import type { Cart, LineItem, UpdateCartItemBody } from '../types'
import { checkoutToCart } from './utils' import { checkoutToCart } from './utils'
import { getCheckoutId, checkoutLineItemUpdateMutation } from '../utils'
import { Mutation, MutationCheckoutLineItemsUpdateArgs } from '../schema' import { Mutation, MutationCheckoutLineItemsUpdateArgs } from '../schema'
export type UpdateItemInput<T = any> = T extends LineItem export type UpdateItemInput<T = any> = T extends LineItem
@ -25,7 +24,8 @@ export default useUpdateItem as UseUpdateItem<typeof handler>
export const handler = { export const handler = {
fetchOptions: { fetchOptions: {
query: checkoutLineItemUpdateMutation, query: 'cart',
method: 'updateItem',
}, },
async fetcher({ async fetcher({
input: { itemId, item }, input: { itemId, item },
@ -46,23 +46,14 @@ export const handler = {
message: 'The item quantity has to be a valid integer', message: 'The item quantity has to be a valid integer',
}) })
} }
const { checkoutLineItemsUpdate } = await fetch< const response = await fetch<Mutation, MutationCheckoutLineItemsUpdateArgs>(
Mutation, {
MutationCheckoutLineItemsUpdateArgs ...options,
>({ variables: [item.itemId, { quantity: item.quantity }],
...options, }
variables: { )
checkoutId: getCheckoutId(),
lineItems: [
{
id: itemId,
quantity: item.quantity,
},
],
},
})
return checkoutToCart(checkoutLineItemsUpdate) return checkoutToCart(response)
}, },
useHook: ({ useHook: ({
fetch, fetch,
@ -75,13 +66,13 @@ export const handler = {
} = {} } = {}
) => { ) => {
const { item } = ctx const { item } = ctx
const { mutate } = useCart() as any const { mutate, data: cartData } = useCart() as any
return useCallback( return useCallback(
debounce(async (input: UpdateItemInput<T>) => { debounce(async (input: UpdateItemInput<T>) => {
const itemId = input.id ?? item?.id const itemId = cartData.lineItems[0].id
const productId = input.productId ?? item?.productId const productId = cartData.lineItems[0].productId
const variantId = input.productId ?? item?.variantId const variantId = cartData.lineItems[0].variant.id
if (!itemId || !productId || !variantId) { if (!itemId || !productId || !variantId) {
throw new ValidationError({ throw new ValidationError({
message: 'Invalid input used for this operation', message: 'Invalid input used for this operation',
@ -91,6 +82,7 @@ export const handler = {
const data = await fetch({ const data = await fetch({
input: { input: {
item: { item: {
itemId,
productId, productId,
variantId, variantId,
quantity: input.quantity, quantity: input.quantity,

View File

@ -17,26 +17,11 @@ export type CheckoutPayload =
const checkoutToCart = (checkoutPayload?: Maybe<CheckoutPayload>): Cart => { const checkoutToCart = (checkoutPayload?: Maybe<CheckoutPayload>): Cart => {
if (!checkoutPayload) { if (!checkoutPayload) {
throw new CommerceError({ throw new CommerceError({
message: 'Invalid response from Shopify', message: 'Invalid response from Swell',
}) })
} }
const checkout = checkoutPayload?.checkout return normalizeCart(checkoutPayload)
const userErrors = checkoutPayload?.userErrors
if (userErrors && userErrors.length) {
throw new ValidationError({
message: userErrors[0].message,
})
}
if (!checkout) {
throw new CommerceError({
message: 'Invalid response from Shopify',
})
}
return normalizeCart(checkout)
} }
export default checkoutToCart export default checkoutToCart

View File

@ -28,12 +28,11 @@ export const handler: SWRHook<
query: getAllProductsQuery, query: getAllProductsQuery,
}, },
async fetcher({ input, options, fetch }) { async fetcher({ input, options, fetch }) {
const { categoryId, brandId } = input const { categoryId, search } = input
const { results, count: found } = await fetch({ const { results, count: found } = await fetch({
query: 'products', query: 'products',
method: 'list', method: 'list',
variables: { category: categoryId }, variables: { category: categoryId, search },
}) })
const products = results.map((product) => normalizeProduct(product)) const products = results.map((product) => normalizeProduct(product))

View File

@ -1,6 +1,26 @@
import * as Core from '@commerce/types' import * as Core from '@commerce/types'
import { CheckoutLineItem } from './schema' import { CheckoutLineItem } from './schema'
export type SwellCart = {
id: string
account_id: number
currency: string
tax_included_total: number
sub_total: number
discount_total: number
quantity: number
items: {
id: string
product: object
price: number
variant: boolean
quantity: number
}
date_created: string
discounts?: { id: number; amount: number }[]
// TODO: add missing fields
}
export interface SwellProduct extends Core.Product { export interface SwellProduct extends Core.Product {
name: string name: string
slug: string slug: string

View File

@ -53,7 +53,6 @@ const normalizeProductImages = (images) =>
})) }))
const normalizeProductVariants = (variants) => { const normalizeProductVariants = (variants) => {
// console.log('variant', variants);
return variants?.map(({ id, name, values, price, stock_status }) => ({ return variants?.map(({ id, name, values, price, stock_status }) => ({
id, id,
name, name,