4
0
forked from crowetic/commerce

Handle validation for duplicated emails

This commit is contained in:
Luis Alvarez 2020-10-19 22:08:01 -05:00
parent 9257b44c0d
commit 0922c87621
2 changed files with 37 additions and 15 deletions

View File

@ -1,3 +1,4 @@
import { BigcommerceApiError } from '../../utils/errors'
import { CustomersHandlers } from '..' import { CustomersHandlers } from '..'
const createCustomer: CustomersHandlers['createCustomer'] = async ({ const createCustomer: CustomersHandlers['createCustomer'] = async ({
@ -12,10 +13,11 @@ const createCustomer: CustomersHandlers['createCustomer'] = async ({
errors: [{ message: 'Invalid request' }], 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 // Passwords must be at least 7 characters and contain both alphabetic
// and numeric characters. // and numeric characters.
try {
const { data } = await config.storeApiFetch('/v3/customers', { const { data } = await config.storeApiFetch('/v3/customers', {
method: 'POST', method: 'POST',
body: JSON.stringify([ body: JSON.stringify([
@ -31,6 +33,26 @@ const createCustomer: CustomersHandlers['createCustomer'] = async ({
}) })
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 export default createCustomer

View File

@ -27,7 +27,7 @@ export type BigcommerceHandlers<T = any> = {
export type BigcommerceApiResponse<T> = { export type BigcommerceApiResponse<T> = {
data: T | null data: T | null
errors?: { message: string }[] errors?: { message: string; code?: string }[]
} }
export default function createApiHandler< export default function createApiHandler<