I have a function that checks if a user is admin or not. If it finds the user id in the database table, it needs to return true, otherwise it needs to return false, but I'm getting undefined. Can you help me?
function isAdmin(useruid) {
db.query("SELECT * FROM admins", function(err,rows,field) {
if(!err) {
rows.forEach(function(element) {
if (useruid === element.uid) {
console.log("[is admin] Found admins!")
return true;
} else {
console.log("[is admin] User is not admin!")
return false;
}
});
} else {
console.log(err);
return false;
}
})
}
I added ; on the missing lines. I'm receiving output of the console.logs, but the function is still returning undefined instead of false or true.
It looks like:
function isAdmin(useruid) {
db.query("SELECT * FROM admins", function(err,rows,field) {
if(!err) {
rows.forEach(function(element) {
if (useruid === element.uid) {
console.log("[is admin] Found admins!");
return true;
} else {
console.log("[is admin] User is not admin!");
return false;
}
});
} else {
console.log(err);
return false;
}
})
}
As noted the solution is more complicated than you might suspect given the asynchronous nature of Node. There are several ways to address the issue your question presents but I'll include just one here that is relatively flexible and lightweight.
The good news is your function isAdmin and the query it includes can be made much simpler so you'll pick up some lines of code there.
Since you start with a UID and your goal is only to check that it exists in the table, you can use a targeted query and skip all the result looping. This will save time and resources in Node as well as MySQL.
Updated Function
Note this is now an async function with a Promise. This way we can later call and await the results. Also the db.query takes an argument for the ? placeholder. We pass it our useruid variable.
const isAdmin = async (useruid) => {
return new Promise((resolve, reject) => {
db.query('SELECT uid FROM admins WHERE uid = ?;', useruid, function (error, results, fields) {
if (error) reject(error);
// when we get our results we can simply check for length
// if we have length, there was a match
// if we have no length, there was no match
resolve(results.length ? true : false)
});
});
};
To call the function…
We must wrap in async function if we want to leverage await
(async function(){
let is_admin = await isAdmin(YOUR_UID_VALUE);
console.log('is_admin', is_admin);
})();