Update cart normalizer

This commit is contained in:
Catalin Pinte 2022-11-15 17:27:20 +02:00
parent 05c537e418
commit 39ba0ab33d
4 changed files with 10 additions and 8 deletions

View File

@ -22,17 +22,17 @@ export const handler: MutationHook<AddItemHook> = {
variables.push(item.variantId)
}
const { cart } = await fetch<{ cart: CommercejsCart }>({
const cart = await fetch<CommercejsCart>({
query: options.query,
method: options.method,
variables,
})
return normalizeCart(cart)
},
useHook: ({ fetch }) =>
function useHook() {
const { mutate } = useCart()
return useCallback(
async function addItem(input) {
const cart = await fetch({ input })

View File

@ -16,7 +16,7 @@ export const handler: MutationHook<RemoveItemHook> = {
method: 'remove',
},
async fetcher({ input, options, fetch }) {
const { cart } = await fetch<{ cart: CommercejsCart }>({
const cart = await fetch<CommercejsCart>({
query: options.query,
method: options.method,
variables: input.itemId,

View File

@ -30,7 +30,7 @@ export const handler = {
},
async fetcher({ input, options, fetch }: HookFetcherContext<UpdateItemHook>) {
const variables = [input.itemId, { quantity: input.item.quantity }]
const { cart } = await fetch<{ cart: CommercejsCart }>({
const cart = await fetch<CommercejsCart>({
query: options.query,
method: options.method,
variables,
@ -57,7 +57,7 @@ export const handler = {
const variantId = input.productId ?? item?.variantId
const quantity = input?.quantity ?? item?.quantity
if (!itemId || !productId || !variantId) {
if (!itemId || !productId) {
throw new ValidationError({
message: 'Invalid input for updating cart item',
})
@ -69,7 +69,7 @@ export const handler = {
item: {
quantity,
productId,
variantId,
variantId: variantId ?? '',
},
},
})

View File

@ -44,14 +44,16 @@ const normalizeLineItem = (
}
}
export const normalizeCart = (commercejsCart: CommercejsCart): Cart => {
export const normalizeCart = (
commercejsCart: CommercejsCart | { cart: CommercejsCart }
): Cart => {
const {
id,
created,
subtotal: { raw: rawPrice },
currency,
line_items,
} = commercejsCart
} = 'cart' in commercejsCart ? commercejsCart.cart : commercejsCart
return {
id,