Vue Storefront is now Alokai! Learn More
AddCartLineItem

AddCartLineItem

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


export const addCartLineItem = defineApi.addCartLineItem(async (context, args) => {
  const cartId = args.cartId ?? getCartId(context);
  const { normalizeCart } = getNormalizers(context);

  if (args.sku == null) {
    throw new Error(
      "Bad Request: missing required argument: `sku`. It is required to add a product to the cart in SAP.",
    );
  }

  const code = args.sku;
  const quantity = args.quantity ?? 1;

  await context.api.createCartEntry({
    cartId,
    orderEntry: {
      quantity,
      product: {
        code,
      },
    },
  });

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

  return normalizeCart(cart);
});