javascript - 抽象中间件函数
问题描述
所以我发现我的中间件 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 - 其中已经有三个,但不确定将第四个放在哪里。
解决方案
您可以使用高阶函数来导出当前函数。您将拥有一个函数,该函数接受角色列表并返回另一个函数,该函数使用该角色列表来检查当前用户是否分配给其中任何一个,如果是,则允许访问:
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");
推荐阅读
- javascript - 如果文本框不为空,请选中复选框
- gantt-chart - 在 DyagrammeR>mermaid>甘特图中更改字体和时间轴标签
- python - 图像不上传到数据库。值错误。'image' 属性没有与之关联的文件
- plsql - Oracle - 如何将记录添加到相同类型的集合中(多集联合)
- nginx - 处理具有不同块的相似位置
- python - 从 list 或 dict 创建 Pandas DataFrame 总是返回空 DF
- guidewire - policyPeriod 上的 EffDated 分支和保存数组
- excel - 如何在数据透视表中将来自 2 个不同列的信息表示为 1?
- amazon-web-services - 如何在 AWS::CloudFormation::Init 中添加 yum 存储库
- python - python 中的方法与类相关联。与实例直接关联的函数意味着什么?