#If statement outside of function is ignored inside of it

7 messages · Page 1 of 1 (latest)

serene flint
#

I have the following code:

if (!req.session.login || !req.session.login.access_token) {
    return res.redirect("http://localhost:3000/v1/auth/login");
}

req.session.regenerate(async (err) => {
    if (err) {
        return res.status(500).json({
            code: 500,
            message: "Something went wrong while processing your request"
        })
    }

    const profileData: auth_profile_data = await OAuthClient.getProfileData(req.session.login.access_token); //req.session.login is possibly undefined
    const account = new accountSchema({
        user_id: profileData.id,
    })
})

But i get the error req.session.login is possibly undefined. If i check for the property to exist with an if statement it should not give me this error but if i move the if statement inside the regenerate callback it will stop erroring.

idle mulch
#

That's because you're passing in an anonymous callback function that has no knowledge of any checks you did outside of it. I would just do the check again, you can shorten it a little using optional chaining

    if (req.session.login?.access_token) {
      const profileData: auth_profile_data = await OAuthClient.getProfileData(req.session.login.access_token); 
      const account = new accountSchema({
          user_id: profileData.id,
      })
    }
glass ivy
#

You can also move it to a constant variable:

const accessToken = req.session.login?.accessToken;

if (!accessToken) {
    return res.redirect("http://localhost:3000/v1/auth/login");
}

req.session.regenerate(async (err) => {
   // can safely use accessToken here
})
idle mulch
serene flint
#

Thanks guys