maitraysuthar/rest-api-nodejs-mongodb

Refactor If Statements.

anuraghazra opened this issue · 1 comments

We can refactor these if statements with Guard Clauses

if (!errors.isEmpty()) {
return apiResponse.validationErrorWithData(res, "Validation Error.", errors.array());
}else {
UserModel.findOne({email : req.body.email}).then(user => {
if (user) {
//Compare given password with db's hash.
bcrypt.compare(req.body.password,user.password,function (err,same) {
if(same){
//Check account confirmation.
if(user.isConfirmed){
// Check User's account active or not.
if(user.status) {
let userData = {
_id: user._id,
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
};
//Prepare JWT token for authentication
const jwtPayload = userData;
const jwtData = {
expiresIn: process.env.JWT_TIMEOUT_DURATION,
};
const secret = process.env.JWT_SECRET;
//Generated JWT token with Payload and secret.
userData.token = jwt.sign(jwtPayload, secret, jwtData);
return apiResponse.successResponseWithData(res,"Login Success.", userData);
}else {
return apiResponse.unauthorizedResponse(res, "Account is not active. Please contact admin.");
}
}else{
return apiResponse.unauthorizedResponse(res, "Account is not confirmed. Please confirm your account.");
}
}else{
return apiResponse.unauthorizedResponse(res, "Email or Password wrong.");
}
});
}else{
return apiResponse.unauthorizedResponse(res, "Email or Password wrong.");
}
});
}
} catch (err) {
return apiResponse.ErrorResponse(res, err);
}
}];

no shit XD