SetCustomerEmail
Implements SetCustomerEmail Unified Method.
Source
import { getNormalizers } from "@alokai/connect/integration-kit";
import { HttpStatusCode } from "@alokai/connect/middleware";
import { cartActions } from "@vsf-enterprise/commercetools-api";
import { defineApi, getCartVersion } from "@vsf-enterprise/unified-api-commercetools";
// Commercetools does not validate the email, so for the consistency with other integrations, we do it by ourserveles
// Regex taken from: https://emailregex.com/
const EMAIL_REGEX =
/^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z-]+\.)+[A-Za-z]{2,}))$/;
export const setCustomerEmail = defineApi.setCustomerEmail(async (context, args) => {
const version = await getCartVersion(context);
const { email } = args;
if (!EMAIL_REGEX.test(email)) {
throw context.createHttpError({
message: "Email does not match the RFC 5322 specification.",
statusCode: HttpStatusCode.BAD_REQUEST,
});
}
const setCustomerEmailAction = cartActions.setCustomerEmail(email);
const { api } = await context.getApiClient();
const updatedCart = await api.updateCart({
...version,
actions: [setCustomerEmailAction],
});
const { normalizeCart } = getNormalizers(context);
return normalizeCart(updatedCart.cart);
});