Tuesday, 25 April 2017

How to do avoid huge nested if else

This is my code for logging in

method: 'POST',
        path: '/api/login/sp',
        config: { auth: false },
        handler: function (request, reply) {
            User.findOne({ phone: request.payload.phone }, function (err, user) {
                if (err) throw err;
                if (user !== null) {
                    user.comparePassword(request.payload.password, function (err, isMatch) {
                        if (err) throw err;
                        if (isMatch) { // Login success
                            data = {
                                "statusCode": 200,
                                "token": generateJWT(user._id)
                            }
                            return reply(data);
                        }
                        else {
                            reply(Boom.unauthorized('Invalid Account'))
                        }
                    });
                }
                else { // Invalid User
                    reply(Boom.unauthorized('Invalid Account'))
                }
            });
        }

It takes a lot of code and makes it very hard to read. Is there a way to better write this part of the code so that it is easily maintainable and readable?



via Eneres

No comments:

Post a Comment