I am building NodeJS/Express authentication and trying some async/await (try/catch) my register route works perfectlfy before i added my validation. The problem is my validaiton (based on validator) is working, is sending back errors as expected but when I have correct data to register user. Postman is returning me empty object. no errors. I am assuming that this try/catch works different then .then() that i used before.
regards
auth.js register route
const db = require('../models')
const validateRegisterInput = require('../validation/register')
exports.register = async (req, res, next) => {
const {
errors,
isValid
} = validateRegisterInput(req.body)
if (!isValid) {
return res.status(400).json(errors)
}
try {
const user = await db.User.create(req.body)
const {
id,
username
} = user
res.json({
id,
username
})
} catch (error) {
return next(error)
}
}
register validation
const validator = require('validator')
const isEmpty = require('./is-empty')
const validateRegisterInput = (data) => {
let errors = {}
data.username = !isEmpty(data.username) ? data.username : ''
data.password = !isEmpty(data.password) ? data.password : ''
if (!validator.isLength(data.username, {
min: 2,
max: 30
})) {
errors.username = 'Username should be between 2 and 30 characters'
}
if (validator.isEmpty(data.username)) {
errors.username = 'Username is required'
}
if (validator.isEmpty(data.password)) {
errors.password = 'Password is required'
}
if (!validator.isLength(data.password, {
min: 6,
max: 30
})) {
errors.password = 'Password should be at least 6 characters'
}
return {
errors,
isValid: isEmpty(errors)
}
}
module.exports = validateRegisterInput
isEMpty
const isEmpty = (value) => {
value === undefined ||
value === null ||
(typeof value === 'object' && Object.keys(value).length === 0) ||
(typeof value === 'string' && value.trim().length === 0)
}
module.exports = isEmpty