Vue Storefront is now Alokai! Learn More
RemoveCartLineItem

RemoveCartLineItem

Implements RemoveCartLineItem 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 RemoveCartLineItemExtendedArgs {
    /**
     * Response configuration. List of fields returned in the response body.
     */
    fields?: "BASIC" | "DEFAULT" | "FULL" | string | string[];
  }
}


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

  const { 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.removeCartEntry({
    cartId,
    entryNumber,
  });

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

  return normalizeCart(updatedCart);
});