Vue Storefront is now Alokai! Learn More
RemoveCartLineItem

RemoveCartLineItem

Implements RemoveCartLineItem Unified Method.

Source

/* eslint-disable max-statements */
import { defineApi } from "@vsf-enterprise/unified-api-commercetools";
import { getNormalizers } from "@vsf-enterprise/unified-api-commercetools/udl";

export const removeCartLineItem = defineApi.removeCartLineItem(async (context, args) => {
  if (args?.cartId != null) {
    throw { statusCode: 400, message: "Multiple carts feature is not available." };
  }
  const me = await context.api.getMe();
  const cart = me.me.activeCart;

  if (!cart) {
    throw new Error("User has no active cart");
  }

  const lineItem = cart.lineItems.find(({ id }: { id: string }) => id === args.lineItemId);

  if (!lineItem) {
    throw new Error("The line item could not be found in the cart");
  }

  const updatedCart = await context.api.removeFromCart(
    {
      id: cart.id,
      version: cart.version,
    },
    {
      ...lineItem,
      id: args.lineItemId,
    },
  );

  const { normalizeCart } = getNormalizers(context);

  return normalizeCart(updatedCart.cart);
});