From 0922c87621a6a34986bf811a1f2e55ed0bc7edf4 Mon Sep 17 00:00:00 2001 From: Luis Alvarez Date: Mon, 19 Oct 2020 22:08:01 -0500 Subject: [PATCH] Handle validation for duplicated emails --- .../api/customers/handlers/create-customer.ts | 50 +++++++++++++------ .../api/utils/create-api-handler.ts | 2 +- 2 files changed, 37 insertions(+), 15 deletions(-) diff --git a/lib/bigcommerce/api/customers/handlers/create-customer.ts b/lib/bigcommerce/api/customers/handlers/create-customer.ts index 73f3738cd..caefeb245 100644 --- a/lib/bigcommerce/api/customers/handlers/create-customer.ts +++ b/lib/bigcommerce/api/customers/handlers/create-customer.ts @@ -1,3 +1,4 @@ +import { BigcommerceApiError } from '../../utils/errors' import { CustomersHandlers } from '..' const createCustomer: CustomersHandlers['createCustomer'] = async ({ @@ -12,25 +13,46 @@ const createCustomer: CustomersHandlers['createCustomer'] = async ({ errors: [{ message: 'Invalid request' }], }) } - // TODO: validate the password. + // TODO: validate the password and email // Passwords must be at least 7 characters and contain both alphabetic // and numeric characters. - const { data } = await config.storeApiFetch('/v3/customers', { - method: 'POST', - body: JSON.stringify([ - { - first_name: firstName, - last_name: lastName, - email, - authentication: { - new_password: password, + try { + const { data } = await config.storeApiFetch('/v3/customers', { + method: 'POST', + body: JSON.stringify([ + { + first_name: firstName, + last_name: lastName, + email, + authentication: { + new_password: password, + }, }, - }, - ]), - }) + ]), + }) - res.status(200).json({ data }) + res.status(200).json({ data }) + } catch (error) { + if (error instanceof BigcommerceApiError && error.status === 422) { + const hasEmailError = '0.email' in error.data?.errors + + // If there's an error with the email, it most likely means it's duplicated + if (hasEmailError) { + return res.status(400).json({ + data: null, + errors: [ + { + message: 'The email is already in use', + code: 'duplicated_email', + }, + ], + }) + } + } + + throw error + } } export default createCustomer diff --git a/lib/bigcommerce/api/utils/create-api-handler.ts b/lib/bigcommerce/api/utils/create-api-handler.ts index 2cb91c534..c6363cb15 100644 --- a/lib/bigcommerce/api/utils/create-api-handler.ts +++ b/lib/bigcommerce/api/utils/create-api-handler.ts @@ -27,7 +27,7 @@ export type BigcommerceHandlers = { export type BigcommerceApiResponse = { data: T | null - errors?: { message: string }[] + errors?: { message: string; code?: string }[] } export default function createApiHandler<