Phil
Phil

Reputation: 3562

Async/Await Request Inside Passport Strategy

I have looked everywhere for an answer that solves this problem, and have tried different suggestions, but I still cannot figure this out.

I'm using the steam API strategy with passport, after creating my new SteamStrategy, I have a callback function that handles my MongoDB collections. I'm basically just checking if the currently logged in user is in the database, if not then create a new User and .save() it into mongoDB.

This all worked fine until I decided I want to make a request() to the steam API for some additional user information that I can store into the new User.

However, when I try to save the request() to a variable and console.log() the variable, it always says null. I know it's because it is running asynchronously, but that's why I used await, but no success. I also tried implementing a callback-hell type of solution, but ran into some severe scoping issues with my final statement of "return done(null, user);"

Anyways. If anyone could explain and provide a solution to my issue that'd be great, thank you!

passport.use(
      new SteamStrategy(
        {
          returnURL: keys.returnURL,
          realm: keys.realm,
          apiKey: keys.steamAPI,
          proxy: true
        },
        async function(identifier, profile, done) {
          const existingUser = await User.findOne({
            steamInfo: { id: profile._json.steamid }
          });

          if (existingUser) {
            middleware.updateMongo(existingUser);
            return done(null, existingUser);
          }

          ////////////////////////THE PROBLEM STARTS HERE/////////////////////
          const steamURL = "hiding url for post";

          const info = await request(steamURL, function(error, response, body) {
            if (!error && response.statusCode == 200) {
              console.log(JSON.parse(body)); //THIS PRINTS OUT THE INFO PERFECTLY
              return JSON.parse(body);
            }
          });


          console.log(info); //THIS WILL ALWAYS SHOW AS NULL OR UNDEFINED

          const user = await new User({
            steamInfo: {
              id: profile._json.steamid,
              persona: info.personaname,
              profileUrl: info.profileurl,
              avatar: info.avatarmedium,
              personaState: info.personastate,
              visibility: info.communityvisibilitystate,
              countryCode: info.loccountrycode
            },
            collectedInfo: { rank: "", reports: "0" }
          }).save();

          return done(null, user);
        }
      )
    );

Upvotes: 4

Views: 2201

Answers (1)

spicypumpkin
spicypumpkin

Reputation: 1219

The problem is that you're using await and a callback at the same time. You shouldn't. Also the request module doesn't use promises - you need request-promise instead, which is basically a wrapper around the request module to let you work with promises.

const request = require("request-promise");

let info = {};
try {
  info = await request(steamURL);
  console.log(info);
}
catch (err) {
  /* Handle error */
}

Upvotes: 2

Related Questions