Home > Software engineering >  How can I set a variable inside a function?
How can I set a variable inside a function?

Time:10-08

got this function to check if the username is an admin.

module.exports = {
 checkAdmin: function(username){
  var _this = this;
  var admin = null;
  sql.execute(sql.format('SELECT * FROM tbl_admins'), (err, result, fields) => {
    if (err) {
        logger.error(err.message);
        return;
    }
    adminArray = []
    result.forEach(element => {
        if(element.Username == username){
            adminArray.push(element.Username)
        }
    });
    
    if (adminArray.includes(username)){
      _this.admin = true;
    }else{
      _this.admin = false;
    }
})
return admin;

} }

And this is in the Express file.

var check = Admin.checkAdmin(req.body.username);
if (check == false) {
  console.log("Wrong")
  res.send({
    message: 'Access denied'
  }); //bad request
  return;
}

The SQL is correct. The problem is to set the variable "admin" inside the SQL function. The function returns "".

Thx

CodePudding user response:

I can't help it but to notice that your whole checkAdmin function has a style I haven't seen before. Let me try to simplify it a bit, maybe it helps with the issue.

// Admin.js

// Return a Promise, so it's easier
// to deal with the asynchronous SQL Call

function checkAdmin (username) {
  return new Promise((resolve, reject) => {

    sql.execute(
      sql.format('SELECT * FROM tbl_admins'),
      (err, result, fields) => {

      if (err) { return reject(err); }

      let foundUser = false;
      result.map((element) => {
        if (element.Username == username) { foundUser = true; }
      });

      return resolve(foundUser);

    });

  });
}

module.exports = { checkAdmin };

  • Related