mirror of
https://github.com/vercel/commerce.git
synced 2025-06-19 13:41:22 +00:00
67 lines
1.8 KiB
TypeScript
67 lines
1.8 KiB
TypeScript
import { Cart, CartItemBody } from '@commerce/types'
|
|
import useAddItem, { UseAddItem } from '@commerce/cart/use-add-item'
|
|
import { CommerceError } from '@commerce/utils/errors'
|
|
import { MutationHook } from '@commerce/utils/types'
|
|
import { useCallback } from 'react'
|
|
import useCart from './use-cart'
|
|
import { cartFragment } from '../api/fragments/cart'
|
|
import { AddItemToOrderMutation } from '../schema'
|
|
import { normalizeCart } from '../lib/normalize'
|
|
|
|
export const addItemToOrderMutation = /* GraphQL */ `
|
|
mutation addItemToOrder($variantId: ID!, $quantity: Int!) {
|
|
addItemToOrder(productVariantId: $variantId, quantity: $quantity) {
|
|
__typename
|
|
...Cart
|
|
... on ErrorResult {
|
|
errorCode
|
|
message
|
|
}
|
|
}
|
|
}
|
|
${cartFragment}
|
|
`
|
|
|
|
export default useAddItem as UseAddItem<typeof handler>
|
|
|
|
export const handler: MutationHook<Cart, {}, CartItemBody> = {
|
|
fetchOptions: {
|
|
query: addItemToOrderMutation,
|
|
},
|
|
async fetcher({ input, options, fetch }) {
|
|
if (
|
|
input.quantity &&
|
|
(!Number.isInteger(input.quantity) || input.quantity! < 1)
|
|
) {
|
|
throw new CommerceError({
|
|
message: 'The item quantity has to be a valid integer greater than 0',
|
|
})
|
|
}
|
|
|
|
const { addItemToOrder } = await fetch<AddItemToOrderMutation>({
|
|
...options,
|
|
variables: {
|
|
quantity: input.quantity || 1,
|
|
variantId: input.variantId,
|
|
},
|
|
})
|
|
|
|
if (addItemToOrder.__typename === 'Order') {
|
|
return normalizeCart(addItemToOrder)
|
|
}
|
|
throw new CommerceError(addItemToOrder)
|
|
},
|
|
useHook: ({ fetch }) => () => {
|
|
const { mutate } = useCart()
|
|
|
|
return useCallback(
|
|
async function addItem(input) {
|
|
const data = await fetch({ input })
|
|
await mutate(data, false)
|
|
return data
|
|
},
|
|
[fetch, mutate]
|
|
)
|
|
},
|
|
}
|