Vue Storefront is now Alokai! Learn More
ApplyCouponToCart

ApplyCouponToCart

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


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

  if (!couponCode) {
    throw new Error("The provided coupon code is empty and cannot be applied.");
  }

  await context.api.doApplyCartVoucher({
    voucherId: couponCode,
    cartId: cartId,
  });

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

  return normalizeCart(updatedCart);
});