I've taken a look at Brad Traversy's User
routes for DevConnector, a project he uses to teach Node.js. The code does not look very clean or self-explanatory enough in my opinion; take a look at the /register
route for example - it's all written in one big block. I am wondering if wrapping promises within other promises can solve this issue.
Below is what my alternative looks like:
router.post('/register', (req, res) => {
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const email = req.body.email;
const password = req.body.password;
const dateOfBirth = req.body.dateOfBirth;
buildUserIfNotExists(email, firstName, lastName, dateOfBirth)
.then(user => hashUserPassword(user, password, 10))
.then(user => saveUser(user))
.then(user => {
sendActivationLink(user);
res.json(user);
})
.catch(errors => {
if (errors.internalError) {
console.log(errors.internalError);
res.status(500).json({
internalError: 'An internal error occured.'
})
} else {
res.status(400).json(errors);
}
});
});
An example of promise wrapper as I see it would be:
function saveUser(user) {
const errors = {};
return new Promise((resolve, reject) => {
user
.save()
.then(user => resolve(user))
.catch(err => {
errors.internalError = err;
reject(errors);
})
});
}
So far I've got no issues with this approach, everything works as expected. Are there any downsides to this that I am missing? Is there any way to simplify this even further?