首页 > 解决方案 > 抽象中间件函数

问题描述

所以我发现我的中间件 Express 函数有重复代码。

第一个功能:

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})
  }
}

第二个功能:

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})
  }
}

我的问题是如何制作一个抽象功能,例如isAllowed(['admin])只有管理员可以通过,或者isAllowed(['admin','recruiter'])它只能允许管理员和招聘人员通过?

我遇到的具体问题是 args - 其中已经有三个,但不确定将第四个放在哪里。

标签: javascriptexpress

解决方案


您可以使用高阶函数来导出当前函数。您将拥有一个函数,该函数接受角色列表并返回另一个函数,该函数使用该角色列表来检查当前用户是否分配给其中任何一个,如果是,则允许访问:

const isRole = (...roles) => async (req, res, next) => {
  try {
    const requestingUser = await knex('users')
                                  .first('current_role')
                                  .where('id','=',req.user.id)
    const isAllowed = roles.some(role => role == requestingUser.current_role);
    isAllowed ? next() : res.sendStatus(403) 

  } catch (error) {
    res.send({error})
  }
}

const isAdmin = isRole("admin");
const isAdminOrRecruiter = isRole("admin", "recruiter");

推荐阅读