Vue Storefront is now Alokai! Learn More
SetCartAddress

SetCartAddress

Implements SetCartAddress Unified Method.

Source

import { defineApi, getNormalizedCart, getShipmentId } from "@vsf-enterprise/unified-api-sfcc";
import type { SfCreateAddressBody, SfCustomerAddress } from "@vsf-enterprise/unified-api-sfcc/udl";
import { getNormalizers } from "@vue-storefront/unified-data-model";


declare module "@vsf-enterprise/unified-api-sfcc" {
  interface SetCartAddressExtendedArgs {
    /**
     * The unique id of the shipment
     */
    shipmentId?: string;
    /**
     * The applied shipping method for the shipment
     */
    shippingMethod?: {
      id: string;
    };
    /**
     * Whether this is a gift shipment for packaging purposes
     */
    gift?: boolean;
    /**
     * Gift message for the shipment, if applicable
     */
    giftMessage?: string;
  }
}


export const setCartAddress = defineApi.setCartAddress(async (context, args) => {
  const { shippingAddress } = args;
  const { unnormalizeAddress } = getNormalizers(context);
  const shipmentId = getShipmentId(context);

  if (!isAddressValid(shippingAddress)) {
    throw { message: "The provided address doesn't have all required fields.", status: 422 };
  }

  const cart = await context.api.updateShipment({
    shipmentId,
    shippingAddress: unnormalizeAddress(shippingAddress),
  });

  return await getNormalizedCart(context, cart);
});

// eslint-disable-next-line complexity
function isAddressValid(address: SfCustomerAddress | SfCreateAddressBody): boolean {
  return Boolean(
    address.address1 &&
      address.city &&
      address.country &&
      address.firstName &&
      address.lastName &&
      address.phoneNumber &&
      address.postalCode &&
      address.state,
  );
}