diff --git a/packages/sylius/src/cart/use-update-item.tsx b/packages/sylius/src/cart/use-update-item.tsx index 950f422e1..8cfb903bf 100644 --- a/packages/sylius/src/cart/use-update-item.tsx +++ b/packages/sylius/src/cart/use-update-item.tsx @@ -1,20 +1,79 @@ -import { MutationHook } from '@vercel/commerce/utils/types' +import { + HookFetcherContext, + MutationHook, + MutationHookContext, +} from '@vercel/commerce/utils/types' import useUpdateItem, { UseUpdateItem, } from '@vercel/commerce/cart/use-update-item' +import { getCartToken } from '../utils/token/cart-token' +import { useCallback } from 'react' +import useCart from './use-cart' +import { LineItem, UpdateItemHook } from '@vercel/commerce/types/cart' +import { ValidationError } from '@vercel/commerce/utils/errors' +import { normalizeCart } from '../utils/normalize/normalize-cart' export default useUpdateItem as UseUpdateItem export const handler: MutationHook = { fetchOptions: { - query: '', + url: '/api/v2/shop/orders', + method: 'PATCH', + }, + fetcher: async ({ + input: { itemId, item }, + options, + fetch, + }: HookFetcherContext) => { + const syliusCart = await fetch({ + url: `${options.url}/${getCartToken()}/items/${itemId}`, + method: options.method, + body: { + quantity: item.quantity, + }, + variables: { + contentType: 'application/merge-patch+json', + }, + }) + return normalizeCart(syliusCart) }, - async fetcher({ input, options, fetch }) {}, useHook: - ({ fetch }) => - () => { - return async function addItem() { - return {} - } + ({ fetch }: MutationHookContext) => + ( + ctx: { + item?: LineItem + wait?: number + } = {} + ) => { + const { item } = ctx + const { mutate, data: cartData } = useCart() as any + + return useCallback( + async function addItem(input) { + const firstLineItem = cartData.lineItems[0] + const itemId = item?.id || firstLineItem.id + const productId = item?.productId || firstLineItem.productId + const variantId = item?.variant.id || firstLineItem.variant.id + if (!itemId) { + throw new ValidationError({ + message: 'Invalid input used for this operation', + }) + } + const data = await fetch({ + input: { + item: { + productId, + variantId, + quantity: input.quantity, + }, + itemId, + }, + }) + console.log('update quantity', data) + await mutate(data, false) + return data + }, + [fetch, mutate] + ) }, } diff --git a/packages/sylius/src/fetcher.ts b/packages/sylius/src/fetcher.ts index 73eecde27..94c5ef53c 100644 --- a/packages/sylius/src/fetcher.ts +++ b/packages/sylius/src/fetcher.ts @@ -9,13 +9,14 @@ const fetcher: Fetcher = async ({ body, variables = { useToken: true, + contentType: 'application/json', }, }) => { const token = getCustomerToken() const res = await fetch(API_URL + url!, { method: method, headers: { - 'Content-Type': 'application/json', + 'Content-Type': variables.contentType, accept: 'application/json, text/plain', ...(token && variables.useToken ? { Authorization: `Bearer ${token}` }