Vue Storefront is now Alokai! Learn More
CreateCustomerAddress

CreateCustomerAddress

Implements CreateCustomerAddress Unified Method.

Source

import { assertAuthorized, defineApi, query } from "@vsf-enterprise/unified-api-magento";
import { getNormalizers } from "@vue-storefront/unified-data-model";
import { resolveRegionId } from "../helpers/resolveRegionId";
import type { CustomerAddress, CustomerAddressInput } from "@vue-storefront/magento-types";

export const createCustomerAddress = defineApi.createCustomerAddress(async (context, args) => {
  await assertAuthorized(context);
  const { address } = args;

  const { unnormalizeAddress, normalizeCustomerAddress } = getNormalizers(context);

  const selectedRegion = await resolveRegionId(context, address);

  const createdAddress = await query(
    context.api.createCustomerAddress({
      ...unnormalizeAddress(address),
      region: {
        region_id: selectedRegion.id,
      },
    } as CustomerAddressInput),
  );

  if (!createdAddress?.createCustomerAddress) {
    throw new Error("Address not created");
  }

  return {
    address: normalizeCustomerAddress(createdAddress.createCustomerAddress as CustomerAddress),
  };
});