我是新来的。尝试根据用户的角色设置中间件来构建字段黑名单,以便常规访问者看不到管理字段。
我似乎无法让事情发挥作用。 app.param()
方法中是否可以有多个中间件?
'use strict';
/**
* Module dependencies.
*/
var businessPolicy = require('../policies/businesses.server.policy'),
business = require('../controllers/businesses.server.controller');
//routes
module.exports = function (app) {
// Business collection routes
app.route('/api/businesses/search/:businessField/:value').all(businessPolicy.isAllowed)
.get(business.read);
app.route('/api/businesses').all(businessPolicy.isAllowed)
.get(business.list)
.post(business.create);
// Single business routes
app.route('/api/businesses/:businessId').all(businessPolicy.isAllowed)
.get(business.read)
.put(business.update)
.delete(business.delete);
// Finish by binding the business middleware
app.param('businessId', business.blacklistFields, business.businessByID);
};
//controller
exports.blacklistFields = function(req, res, next){
//create a blacklist of fields based on role here
next();
}
exports.businessByID = function (req, res, next, id) {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).send({
message: 'Business is invalid'
});
}
Business.findById(id).populate('user', 'displayName').select(/*blacklist fields here*/ ).exec(function (err, business) {
if (err) {
return next(err);
} else if (!business) {
return res.status(404).send({
message: 'No businesses with that identifier has been found'
});
}
req.business = business;
next();
});
};
答案 0 :(得分:0)
我似乎无法让事情发挥作用。是否可以在app.param()方法中使用多个中间件?
没有
Docs表示只收到一个回调(而不是多个符号,例如。.delete()
)。
您可以在blacklistFields
或其他businessByID()
中加载您的app.param('user', ...)
,例如根据用户角色blacklistFields
填充的内容。
您可以在其他位置设置所需的中间件,例如:app.route('/api/*').all(fillBlacklistFields)
请注意:
中间件功能是按顺序执行的,因此中间件包含的顺序非常重要。