I'm currently working on developing an API using Express and Sequelize. Specifically, I am writing a function to create a new user where I utilize bcrypt for password hashing.
const createNewUser = (data) => {
return new Promise(async (resolve, reject) => {
try {
let check = await checkUserEmail(data.email)
if (check === true) {
resolve({
errcode: 1,
errMessage: 'Your email is already exist!',
})
}
let hashPassWordFromBcrypt = await hashUserPassWord(data.passWord)
await db.User.create({
email: data.email,
passWord: hashPassWordFromBcrypt,
firstName: data.firstName,
lastName: data.lastName,
address: data.address,
phoneNumber: data.phoneNumber,
gender: data.gender === '1' ? true : false,
roleId: data.roleId,
})
resolve({
errcode: 0,
errMessage: 'OK',
})
} catch (error) {
reject(error)
}
}) }
const salt = bcrypt.genSaltSync(10)
const hashUserPassWord = (password) => {
return new Promise(async (resolve, reject) => {
try {
let hashPassWord = await bcrypt.hashSync(password, salt)
resolve(hashPassWord)
} catch (error) {
reject(error)
}
})
}
const checkUserEmail = (email) => {
return new Promise(async (resolve, reject) => {
try {
const user = await db.User.findOne({ where: { email } })
if (user) {
resolve(true)
}
resolve(false)
} catch (e) {
reject(e)
}
})
}
While testing with Postman, I encountered a problem. When sending data with an email that already exists, the response shows errCode: 1
and
errMessage: Your email is already exist
, but a new user is still created with the same email. However, when posting a request with an already existing email and without a password, no new user is created.
I need assistance to rectify this issue. Thank you!