RegisterCustomer
Implements RegisterCustomer
Unified Method.
Source
import { defineApi, getCartFromContext } from "@vsf-enterprise/unified-api-sapcc";
import { AUTH_USER_ID_COOKIE_NAME, AUTH_USER_TOKEN_COOKIE_NAME } from "@vsf-enterprise/sapcc-api";
import { getNormalizers } from "@vsf-enterprise/unified-api-sapcc/udl";
import { UserSignUpProps } from "@vsf-enterprise/sapcc-types";
declare module "@vsf-enterprise/unified-api-sapcc" {
interface RegisterCustomerExtendedArgs {
/**
* Response configuration. List of fields returned in the response body.
*/
fields?: "BASIC" | "DEFAULT" | "FULL" | string | string[];
/**
* The customer fields to be included in created user.
*/
customer?: Partial<Pick<UserSignUpProps, "titleCode">>;
}
}
export const registerCustomer = defineApi.registerCustomer(async (context, args) => {
const { email, firstName, lastName, password } = args;
const { normalizeCustomer } = getNormalizers(context);
const cart = await getCartFromContext(context);
const { data: user } = await context.api.createUser({
userSignUp: {
firstName: firstName,
lastName: lastName,
uid: email,
password: password,
},
});
if (context.req.cookies[AUTH_USER_TOKEN_COOKIE_NAME]) {
// ASM agent is logged in and will start emulating registered user
context.res.cookie(AUTH_USER_ID_COOKIE_NAME, user.customerId);
} else {
const loginData = await context.extendedApi.auth.OAuthUserAuthorization({
username: email,
password: password,
});
context.req.cookies[AUTH_USER_TOKEN_COOKIE_NAME] = JSON.stringify(loginData.token);
}
const shouldCreateNewCartBasedOnGuestCart = cart.totalItems && cart.guid;
if (shouldCreateNewCartBasedOnGuestCart) {
await context.api.createCart({
oldCartId: cart.guid,
});
}
return {
customer: normalizeCustomer(user),
};
});