Vue Storefront is now Alokai! Learn More
RemoveCartLineItem

RemoveCartLineItem

Implements RemoveCartLineItem Unified Method.

Source

import { HttpStatusCode, NotFoundError } from "@alokai/connect/middleware";
import { CartIncludeEnum } from "@vsf-enterprise/bigcommerce-api";

import { defineApi, getCartFromContext } from "@vsf-enterprise/unified-api-bigcommerce";
import { findCartItemById, getNormalizedCart } from "@vsf-enterprise/unified-api-bigcommerce";

export const removeCartLineItem = defineApi.removeCartLineItem(async (context, args) => {
  if (args?.cartId != null) {
    throw context.createHttpError({
      message: "Multiple carts feature is not available.",
      statusCode: HttpStatusCode.BAD_REQUEST,
    });
  }
  const cart = await getCartFromContext(context);

  const { lineItemId } = args;
  const cartId = cart.id as string;
  const isLineItemFound = findCartItemById(cart, lineItemId);

  if (!isLineItemFound) {
    throw new NotFoundError(`Line item with id ${lineItemId} not found in the cart`);
  }

  const { api } = await context.getApiClient();
  const { data: updatedCart } = await api.removeCartItem({
    cartId,
    include: CartIncludeEnum.LineItemsPhysicalItemsOptions,
    itemId: lineItemId,
  });

  if (updatedCart) {
    return await getNormalizedCart(context, updatedCart);
  }

  const createdCart = await api.createCart({
    data: {
      line_items: [],
    },
  });

  return await getNormalizedCart(context, createdCart.data);
});