I search for rails-like way of writing NodeJS code and it's more then hard to find the right way. The code quickly become bloated and unreadable. I would like my code to be as clean as possible.
Example (common ExpressJS middleware API controller):
var User = require('../models/user'); // mongoose model
exports.updateUser = function(req, res, next) {
User.passwordToSecretWithBcrypt(req.body.password, function(err, secret) {
if (err) return next(err);
User.findById(req.user.id).exec(function(err, user) {
if (err) return next(err);
if (!user) return next(new Error('no user found'));
if (req.body.name) user.name = req.body.name;
if (req.body.email) user.email = req.body.email;
if (secret) user.secret = secret;
user.save(function(err, user) {
if (err) return next(err);
if (!user) return next(new Error('user not saved'));
res.json(user);
});
});
});
};
The main question is the error handling. A simple record update in the example above has 5 error handling statements. That's crazy in my opinion and you never know exactly what kind of error you'll get so it's very hard to construct the JSON error response that is shown to a user.
Is there a better way for handling errors?
I also tried to use promises
but I couldn't find a best-practice
example that would show me the whole example as a chain of the find, save, create and delete Mongoose methods.
How can I convert the example above to use promises
?
Would promises fix the error handling? If so, how (question1)?