我创建了一个带有参数companyIdSource和数组的checkCompanyPermit函数。
示例:
companyIdSouce: "req.body.companyId", "req.params.companyId"...
allowed: "user", "admin"...
使用参数companyIdSource作为字符串,我想将其转换为数据。如果我使用eval(companyIdSource)
可以使用,但是很糟糕。我该怎么办?
我尝试使用Function("return " + companyIdSource)()
,但返回错误:未定义req。
const checkCompanyPermit = (companyIdSource, ...allowed) => {
return async (req, res, next) => {
try {
const companyId = eval(companyIdSource) //Bad code, change another code
const company = await Company.findById(companyId)
//... some code
} catch (error) {
next(error)
}
}
}
checkCompanyPermit("req.body.companyId", "manager")
答案 0 :(得分:1)
由于您已经可以访问中间件中的req
对象,因此无需传递req.body.companyId
的完整字符串表示形式,仅需要检查的属性就足够了。使用bracket notation来访问req.body对象的值,即
const checkCompanyPermit = (companyIdSource, allowed) => {
return async (req, res, next) => {
try {
const companyId = req.body[companyIdSource]
const company = await Company.findById(companyId)
//... some code
} catch (error) {
next(error)
}
}
}
checkCompanyPermit("companyId", "manager")
答案 1 :(得分:0)
为您工作。
const ObjectId = require('mongodb').ObjectId;
const checkCompanyPermit = (companyIdSource, ...allowed) => {
return async (req, res, next) => {
try {
const companyId = ObjectId('companyIdSource') //Replace here new code
const company = await Company.findById(companyId)
//... some code
} catch (error) {
next(error)
}
}
}
checkCompanyPermit("req.body.companyId", "manager")