Vue Storefront is now Alokai! Learn More
RegisterCustomer

RegisterCustomer

Implements RegisterCustomer Unified Method.

Source

import { defineApi } from "@vsf-enterprise/unified-api-sfcc";
import { validatePassword } from "@vsf-enterprise/unified-api-sfcc/udl";
import { methods } from "@vsf-enterprise/unified-api-sfcc";
const { loginCustomer } = methods;

import { Customer } from "@vsf-enterprise/sfcc-types";
import { KnownKeys } from "@vsf-enterprise/unified-api-sfcc";
declare module "@vsf-enterprise/unified-api-sfcc" {
  interface RegisterCustomerExtendedArgs {
    /**
     * The additional customer object fields to be created. Excluding `firstName`, `lastName`, `email`, and `login`.
     * {@link https://developer.salesforce.com/docs/commerce/commerce-api/references/shopper-customers?meta=registerCustomer SFCC method reference}
     */
    customer?: Partial<Omit<KnownKeys<Customer>, "firstName" | "lastName" | "email" | "login">>;
  }
}


export const registerCustomer = defineApi.registerCustomer(async (context, args) => {
  const { email, firstName, lastName, password } = args;

  if (!validatePassword(password, password)) {
    // eslint-disable-next-line etc/throw-error
    throw { message: "Password does not meet the requirements", code: 422 };
  }
  const basket = await context.api.getBasket();

  try {
    await context.api.register({
      customer: {
        firstName: firstName,
        lastName: lastName,
        email: email,
        login: email,
      },
      password: password,
    });
  } catch {
    throw { statusCode: 400, message: "Could not register customer" };
  }

  const loggedInCustomer = await loginCustomer(context, { email, password });

  if (basket && basket.productItems?.length) {
    await context.api.setBasketCustomerInfo({
      basketId: basket.basketId,
      email,
    });
  }

  return loggedInCustomer;
});