Reputation: 355
This is my signup route :
hashed = await bcrypt.hash(req.body.password, bcryptRounds).catch(() => {
res.status(500).send();
return (null);
});
if (hashed === null) {
return;
}
result = await database.collection("profiles").insertOne({ "username": req.body.username, "password": hashed }).catch(() => {
res.status(500).send();
return (null);
});
if (result === null) {
return;
}
cookie = await SetAuthentification(result.ops[0]._id).catch((err) => {
res.status(500).send();
return (null);
});
if (cookie === null) {
return;
}
SetAuthentificationCookie(cookie, res);
res.status(200).send();
I need to return (null) after every catch and check it to make sure that it didn't fail, but this takes a lot of place and my code is becoming less clear compare to what I had before (but didn't worked in case of error)
hashed = await bcrypt.hash(req.body.password, bcryptRounds).catch(() => {
res.status(500).send();
});
result = await database.collection("profiles").insertOne({ "username": req.body.username, "password": hashed }).catch(() => {
res.status(500).send();
});
cookie = await SetAuthentification(result.ops[0]._id).catch((err) => {
res.status(500).send();
});
SetAuthentificationCookie(cookie, res);
res.status(200).send();
Any idea on how to improve that part to make it clearer ?
Upvotes: 0
Views: 52
Reputation: 1182
Why don't you just wrap everything into try...catch
?:
try {
const hashed = await bcrypt.hash(req.body.password, bcryptRounds);
const result = await database.collection("profiles").insertOne({
username: req.body.username,
password: hashed,
});
const cookie = await SetAuthentification(result.ops[0]._id);
SetAuthentificationCookie(cookie, res);
res.status(200).send();
} catch (err) {
res.status(500).send();
}
If any of the promises reject, the code execution jumps to catch
block.
Upvotes: 1