Struggling to implement and grasp async await functions
in my login example, I'm uncertain if my code is the most optimal, elegant, and clean. I especially have doubts regarding error handling, and how to best utilize const and functional programming principles. I would greatly appreciate any feedback or opinions!
app.post('/', async (req, res) => {
try {
const { email } = req.body.email; // using destructuring
const foundUser = await User.findOne({email: email});
// Check if user exists
if (!foundUser) { // return null if not found
throw res.status(404).json({error: 'User not found'});
}
// Validate user password
if (!bcrypt.compareSync(req.body.password, foundUser.password)) {
throw res.status(404).json({error: 'Password does not match'});
}
const token = jwt.sign( // generate token
{
user: foundUser
},
SEED,
{
expiresIn: (60 * 60)
}
);
res.status(200).json({ // send response
token: token,
user: foundUser
});
} catch (error) { // handle errors
res.status(404).json(error);
}
}
THANKS