I don't know how to formule the question(title), so I'll just say it here, and maybe someone may help or provide a new point of view about it.
I'm working with discord.js and I want to check if user has a role/roles from a message
client.on('message', message => {
if (message.member.roles.find(r => r.name === 'ADMIN')) {
console.log('I am admin');
}
});
Now my idea is to make this a polymorphism functions, because if I want to check two roles I have to do this:
client.on('message', message => {
if (message.member.roles.find(r => r.name === 'ADMIN') || message.member.roles.find(r => r.name === 'Other')) {
console.log('I am admin');
}
});
And I would like to move this if condition to a function and it will check it even if I want to check one or more `permissions.
For now I have tried to deal with it, but nothing, and stopped here... Maybe someone can give me some advice or other point of view. The idea is to prevent duplicate code and an if as long as the width of my monitor.
function hasRole(msg, permissions, condition = 'or') {
if (Array.isArray(permission)) {
if (condition === 'or') {
permissions.forEach(function (element) {
});
// permission.join('||');
return msg.member.roles.find(r => r.name === permissions) ||
msg.member.roles.find(r => r.name === permissions);
} else if (condition === 'and') {
}
}
return msg.member.roles.find(r => r.name === permissions);
}
If you want to check DiscordJS DOCS.
Response:
function checkPermissions(msg, permissions, condition = 'or') {
if (condition === 'or') {
return msg.member.roles.some(r => permissions.includes(r.name));
} else if (condition === 'and') {
return msg.member.roles.every(r => permissions.includes(r.name));
}
}