I am writing a sign-in function with my express app and do not like the fact that in the callback chain, lots of res.status(500).send(body)
are duplicated:
router.post('/login', (req, res) => {
User.findOne({
where: { username: req.body.username }
})
.then( user => {
if (user) {
User.verifyPassword(req.body.password, user)
.then((verified) => {
if (verified) {
let signedToken = jwt.sign(
{ user: user.id },
'secret',
{ expiresIn: 24 * 60 * 60 }
);
res.status(200).send({
token: signedToken,
userId: user.id,
username: user.username
});
} else {
// If password entered does not match user password
res.status(500).send({ error: true, });
}
})
// If bycrpt explodes
.catch((error) => {
res.status(500).send({ error: error, });
});
} else {
// If we can't even find a user with that username
res.status(500).send({ error: true, });
}
})
// If the db query to find a user explodes
.catch(error => {
res.status(500).send({ error: error });
});
});
Two of these are related to vague exceptions occurring that make the API blow up. The other two are based on boolean values returned by the APIs. I am not much of a back end engineer and this is just a personal project, but I want to know what are the best practices for this in the Node.js world.
While we're at it, I'm not sure what the appropriate status code to send in these error cases would be, as I am sure 500 is not correct.