I am currently working on a script that checks if a username is available or already taken. When the username is found to be taken, I need to assign an error message to my errors object. However, I am struggling with passing these errors from the inner if statement to the outer return statement. Can anyone suggest a solution for this problem?
exports.reduceUserDetails = data => {
let errors = {}
const userRef = db.collection('users').where('username', '==', data.username)
userRef.get().then(snapshot => {
if (!snapshot.empty) {
errors.username = 'Username is already taken'
} else {
console.log('Username is available')
}
})
return {
errors,
valid: Object.keys(errors).length === 0 ? true : false
}
}
This is where I'm implementing the reduceUserDetails function:
exports.profileUpdate = (req, res) => {
let userDetails = req.body
const { valid, errors } = reduceUserDetails(userDetails)
if (!valid) return res.status(400).json(errors)
let document = db
.collection('users')
.where('username', '==', req.user.username)
document
.get()
.then(snapshot => {
snapshot.forEach(doc => {
const data = doc.id
db.collection('users').doc(data).update(req.body)
})
res.json({ message: 'Update Successful' })
})
.catch(error => {
console.error(error)
return res.status(400).json({
message: 'Failed to Update'
})
})
}