4
0
forked from crowetic/commerce

Moved create customer API to signup method

This commit is contained in:
Luis Alvarez 2020-10-21 09:15:14 -05:00
parent c2b3152153
commit f0a2c744e8
2 changed files with 118 additions and 0 deletions

View File

@ -0,0 +1,68 @@
import { BigcommerceApiError } from '../../utils/errors'
import login from '../../operations/login'
import { SignupHandlers } from '../signup'
const signup: SignupHandlers['signup'] = async ({
res,
body: { firstName, lastName, email, password },
config,
}) => {
// TODO: Add proper validations with something like Ajv
if (!(firstName && lastName && email && password)) {
return res.status(400).json({
data: null,
errors: [{ message: 'Invalid request' }],
})
}
// TODO: validate the password and email
// Passwords must be at least 7 characters and contain both alphabetic
// and numeric characters.
let result: { data?: any } = {}
try {
result = await config.storeApiFetch('/v3/customers', {
method: 'POST',
body: JSON.stringify([
{
first_name: firstName,
last_name: lastName,
email,
authentication: {
new_password: password,
},
},
]),
})
} 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
}
console.log('DATA', result.data)
// TODO: Currently not working, fix this asap.
const loginData = await login({ variables: { email, password }, config })
console.log('LOGIN DATA', loginData)
res.status(200).json({ data: result.data ?? null })
}
export default signup

View File

@ -0,0 +1,50 @@
import createApiHandler, {
BigcommerceApiHandler,
BigcommerceHandler,
} from '../utils/create-api-handler'
import isAllowedMethod from '../utils/is-allowed-method'
import { BigcommerceApiError } from '../utils/errors'
import signup from './handlers/signup'
export type SignupBody = {
firstName: string
lastName: string
email: string
password: string
}
export type SignupHandlers = {
signup: BigcommerceHandler<null, { cartId?: string } & Partial<SignupBody>>
}
const METHODS = ['POST']
const signupApi: BigcommerceApiHandler<null, SignupHandlers> = async (
req,
res,
config,
handlers
) => {
if (!isAllowedMethod(req, res, METHODS)) return
const { cookies } = req
const cartId = cookies[config.cartCookie]
try {
const body = { ...req.body, cartId }
return await handlers['signup']({ req, res, config, body })
} catch (error) {
console.error(error)
const message =
error instanceof BigcommerceApiError
? 'An unexpected error ocurred with the Bigcommerce API'
: 'An unexpected error ocurred'
res.status(500).json({ data: null, errors: [{ message }] })
}
}
const handlers = { signup }
export default createApiHandler(signupApi, handlers, {})