Search code examples
node.jsnode-postgres

Promise with node-postgres queries always returns undefined


I have a problem to evaluate the result of a function that use node-postgres query, it allways return "undefined" (this function verify JWT token informations validity in database):

const testTokenQuery = function(account_id, is_admin, query) {
  return new Promise(function(resolve, reject){
    pool.query(query, [account_id], function(err, result) {
        if(err) {
          reject("invalid")
        }
        else {
          const bdd_account_id = String(JSON.stringify(result.rows[0].ac_account_id)).replace(/['"]+/g, '')
          const bdd_is_admin = String(JSON.stringify(result.rows[0].ac_isadmin)).replace(/['"]+/g, '')
          if (account_id == bdd_account_id || tok_is_admin == bdd_is_admin){
            resolve ("valid")
          }
          else {
            reject("invalid")
          }

        }
    })
    pool.end();
  })
}

const testToken = (token) => {
  const checkTokenId_query = sql = fs.readFileSync('./sqlqueries/checkTokenId_query.sql').toString()
  const decodedToken = jwt.decode(token, 'JWT_SIGN_SECRET')
  const tok_account_id = decodedToken.account_id
  const tok_is_admin = decodedToken.isadmin
  testTokenQuery(tok_account_id, tok_is_admin, checkTokenId_query)
    .then(function(result){
      console.log(result) //===================> It allways return the good value here
  }).catch(function(err){
    console.log(err);   
  })
}


const isvalid = testToken('eyJhbGciO............ltJT0PhXCjV00')
if(isvalid == "valid") {
  console.log("valid token")
}
else if(isvalid == "invalid") {
  console.log("not a valid token")
}
else{
  console.log("I don't know : " + isvalid) //======> Always the result with isvalid = undefined
}

The SQL Query file contains :

SELECT  ac_account_id,
            ac_isadmin,
            ac_isactive
FROM    table_accounts
WHERE ac_account_id = $1;

The result is always "I don't know : undefined" while the console.log(result) of the testTokenQuery .then returns "valid"...

I tested with callbacks : same problem, await/async : same problem ... I am going crazy ...

Thanx for help !

Regards.

UPDATE : I tried to simplified at the extreme to test with async but I still have "undefined" as an answer :

const testTokenQuery = async (account_id, query) => {
    pool.query(query, [account_id], function(err, result) {
      return String(JSON.stringify(result.rows[0].ac_account_id))
    })
}
const testToken = async (token) => {
    const checkTokenId_query = sql = fs.readFileSync('./sqlqueries/checkTokenId_query.sql').toString()
    const decodedToken = jwt.decode(token, 'JWT_SIGN_SECRET')
    const tok_account_id = decodedToken.account_id
    return await testTokenQuery(tok_account_id, checkTokenId_query)
}

const tokenReturn = async (token) => {
    console.log(await testToken(token))
}

tokenReturn('eyJhbGciOiJ...........0PhXCjV00')

Solution

  • Honestly I didn't used "node-query" before, but I've just explored this issue talk (this about .end(), so I don't think that's a problem).

    From your codes I believe the reason is that you call the functions itself, but not the callback (not the resolved) result. I think you can implement this with async-await. It's not the complete code. As in the last part I need to call async function, so I did that with scoped function, but you can change that for your needs.

    Try something like this:

    const testTokenQuery = async (account_id, is_admin, query) => {
        pool.query(query, [account_id], function(err, result) {
            if(err) {
                return "invalid";
            } else {
                const bdd_account_id = String(JSON.stringify(result.rows[0].ac_account_id)).replace(/['"]+/g, '')
                const bdd_is_admin = String(JSON.stringify(result.rows[0].ac_isadmin)).replace(/['"]+/g, '')
                if (account_id == bdd_account_id || tok_is_admin == bdd_is_admin){
                    return "valid";
                } else {
                    return "invalid";
                }
            }
        });
    }
    
    const testToken = async (token) => {
        const checkTokenId_query = sql = fs.readFileSync('./sqlqueries/checkTokenId_query.sql').toString()
        const decodedToken = jwt.decode(token, 'JWT_SIGN_SECRET')
        const tok_account_id = decodedToken.account_id
        const tok_is_admin = decodedToken.isadmin
        
        return await testTokenQuery(tok_account_id, tok_is_admin, checkTokenId_query)
    }
    
    (async () => {
        const isvalid = await testToken('eyJhbGciO............ltJT0PhXCjV00')
        if(isvalid == "valid") {
            console.log("valid token")
        } else if(isvalid == "invalid") {
            console.log("not a valid token")
        } else {
            console.log("I don't know : " + isvalid) //======> Always the result with isvalid = undefined
        }
    })();