Vue Storefront is now Alokai! Learn More
RegisterCustomer

RegisterCustomer

Implements RegisterCustomer Unified Method.

Source

import "./extended";
import { validatePassword } from "@alokai/connect/integration-kit";
import { HttpStatusCode } from "@alokai/connect/middleware";
import { z } from "zod";

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

const argsSchema = z.object({
  email: z.string().email(),
  firstName: z.string().min(1),
  lastName: z.string().min(1),
  password: z.string().min(1),
});

export const registerCustomer = defineApi.registerCustomer(async (context, args) => {
  argsSchema.parse(args);

  const { api } = await context.getApiClient();
  const { email, firstName, lastName, password } = args;

  if (!validatePassword(password, password)) {
    throw context.createHttpError({
      message: "Password does not meet the requirements",
      statusCode: HttpStatusCode.UNPROCESSABLE_ENTITY,
    });
  }
  const basket = await api.getBasket();

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

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

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

  return loggedInCustomer;
});