Vue Storefront is now Alokai! Learn More
UpdateCartLineItem

UpdateCartLineItem

Implements UpdateCartLineItem Unified Method.

Source

import { defineApi, getCartId } from "@vsf-enterprise/unified-api-sapcc";
import { getNormalizers } from "@vsf-enterprise/unified-api-sapcc/udl";


declare module "@vsf-enterprise/unified-api-sapcc" {
  interface UpdateCartLineItemExtendedArgs {
    /**
     * Response configuration. List of fields returned in the response body.
     */
    fields?: "BASIC" | "DEFAULT" | "FULL" | string | string[];
  }
}


export const updateCartLineItem = defineApi.updateCartLineItem(async (context, args) => {
  const cartId = args.cartId ?? getCartId(context);
  const { data: cart } = await context.api.getCart({ cartId });

  const { quantity, lineItemId } = args;
  const { normalizeCart } = getNormalizers(context);

  const entryNumber = cart.entries?.find((item) => item.product?.code === lineItemId)?.entryNumber;

  if (entryNumber == null) {
    throw new Error(`Line item with id ${lineItemId} not found in the cart`);
  }

  await context.api.updateCartEntry({
    cartId,
    entryNumber,
    orderEntry: {
      quantity,
    },
  });

  const { data: updatedCart } = await context.api.getCart({ cartId });

  return normalizeCart(updatedCart);
});