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 "@vue-storefront/unified-data-model";
import { getNormalizers } from "@vue-storefront/unified-data-model";
import "./extended.d";

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,
  );
}