I'm writing a really simple RESTful API using Node.js, restify and mongoose but the code is getting complex and long. This is caused by all the checks that I have to do every time I make a query. For example, the next code show the controller for the endpoint POST /users/:user1/follow/:user2.
exports.followUser = function(req, res, next) {
User.findOne({ username: req.params.user1 }, function(err, user1) {
if (err) {
res.status(500);
res.json({ type: false, data: 'Error occurred: ' + err });
} else {
if (user1) {
User.findOne({ username: req.params.user2 }, function(err, user2) {
if (err) {
res.status(500);
res.json({ type: false, data: 'Error occurred: ' + err });
} else {
if (user2) {
user2.followers.push(user1);
user2.save();
res.json({
type: true,
data: 'User ' + req.params.user1 + ' is now following user ' + req.params.user2
});
} else {
res.json({
type: false,
data: 'User ' + req.params.user2 + ' not found'
});
}
}
});
} else {
res.json({
type: false,
data: 'User ' + req.params.user1 + ' not found'
});
}
}
});
};
How can I simplify this code? As you can see I'm checking the result of each findOne to know if the users received exist and I'm also returning json answers for each error but this is tedious. Is there a way to automatize this?