LoginCustomer
Implements LoginCustomer Unified Method.
Source
import { getNormalizers } from "@alokai/connect/integration-kit";
import { HttpStatusCode } from "@alokai/connect/middleware";
import { COOKIE_KEY_CUSTOMER_DATA } from "@vsf-enterprise/bigcommerce-api";
import { defineApi } from "@vsf-enterprise/unified-api-bigcommerce";
const MESSAGE_LOGIN_ERROR = "Could not login customer";
const MESSAGE_ALREADY_LOGGED_IN = "Customer is already logged in";
export const loginCustomer = defineApi.loginCustomer(async (context, args) => {
if (context.req.cookies[COOKIE_KEY_CUSTOMER_DATA]) {
throw context.createHttpError({
message: MESSAGE_ALREADY_LOGGED_IN,
statusCode: HttpStatusCode.FORBIDDEN,
});
}
const { api } = await context.getApiClient();
const loginData = await api.loginCustomer(args);
const { normalizeCustomer } = getNormalizers(context);
if (!loginData.is_valid) {
throw context.createHttpError({
message: MESSAGE_LOGIN_ERROR,
statusCode: HttpStatusCode.UNAUTHORIZED,
});
}
context.req.cookies[COOKIE_KEY_CUSTOMER_DATA] = loginData.token;
const {
data: { 0: user },
} = await api.getCustomers({});
if (!user) {
throw context.createHttpError({
message: MESSAGE_LOGIN_ERROR,
statusCode: HttpStatusCode.NOT_FOUND,
});
}
return { customer: normalizeCustomer(user) };
});