Monday 1 May 2017

Mongoose seems to satisfy wrong promise (node js)

I am trying to refactor some inherited code. In every endpoint was the same validation code. I want to pull it out into it's own method. I am new to promises, but I think that is what I want to use. The issues is prom seems to be resolved at the User.findOne call and exits with an undefined prom.promise.

cheers bob

function validateUser(req) {
    var prom = q.defer();
    var token = getToken(req.headers);
    if (token) {
        console.log("have a token")
        var decoded = jwt.decode(token, config.secret);
        console.log("now going to look for the user")
       //Problem exit is on next line
        User.findOne({
            name: decoded.name
        }, function (err, user) {
            if (err) throw err;
                prom.reject(err);
            if (!user) {
                console.log("no user found")
                prom.reject("Authentication failed. User not found.")

            } else {
                console.log("user found returning true")
                prom.resolve(true);

            }
        })

    } else {
        console.log("no token found")
        prom.reject("No token provided.")
    }
    return prom.promise;
}



via Bob Cummings

No comments:

Post a Comment