After reviewing my middleware Express functions, I realized that there is repeated code.
The first function is as follows:
const isAdmin = async (req, res, next) => {
try {
const requestingUser = await knex('users')
.first('current_role')
.where('id','=',req.user.id)
requestingUser.current_role !== 'admin' ? res.sendStatus(403) : next()
} catch (error) {
res.send({error})
}
}
The second function is:
const isAdminOrRecruiter = async (req, res, next) => {
try {
const requestingUser = await knex('users')
.first('current_role')
.where('id','=',req.user.id)
const isNotAllowed = requestingUser.current_role !== 'admin' && requestingUser.current_role !== 'recruiter'
isNotAllowed ? res.sendStatus(403) : next()
} catch (error) {
res.send({error})
}
}
I am now considering how to create a single abstract function like isAllowed(['admin])
for only allowing admin access, or isAllowed(['admin','recruiter'])
for permitting admins and recruiters to pass through. How can I achieve this efficiently?
The issue I face currently pertains to the arguments - there are already three of them, leaving me uncertain about where to add a fourth one.