I am trying to achieve proper post validation which is eloquent and DRY when using Express.JS. What is the best way to do this properly?
Here is a code snipped where I trying make sure that this POST route will not crash the Node.js server and is type safe. But I feel that this is an ugly way to achieve this:
app.post('/signup', function(req, res) {
if(typeof req.body.name !== 'string' || typeof req.body.email !== 'string' || typeof req.body.password !== 'string' ){
res.status(400).send({status:400, message: 'Invalid json post format', type:'client'});
}else{
User.findOne({
name: req.body.name
}, function(err, user) {
if (err) throw err;
if (!user) {
User.findOne({
email: req.body.email
}, function(err, user) {
if (err) throw err;
if (!user) {
//both username and email are neither in use so lets create a user
var passwordToSave = bcrypt.hashSync(req.body.password, salt);
var user = new User({
name: req.body.name,
email: req.body.email,
password: passwordToSave,
admin: false
});
user.save(function(err) {
if (err) throw err;
console.log('User created successfully');
res.json({ success: true });
});
} else if (user) {
res.json({ success: false, message: 'Signup failed. Username already in use.' });
}
});
} else if (user) {
res.json({ success: false, message: 'Signup failed. Username already in use.' });
}
});
}});