Mar*_*aer 5 sails.js waterline
假设我有这个模型:
module.exports = {
attributes: {
title: {
type: 'string',
required: true
},
content: {
type: 'string',
required: true
},
createdBy: {
type: 'string',
required: true
}
}
}
Run Code Online (Sandbox Code Playgroud)
我需要将当前用户ID设置为模型的createdBy属性.我以为我可以使用beforeValidate生命周期回调来做到这一点,但我无法访问存储当前用户的请求对象.有没有办法访问它,或者我应该以其他方式解决这个问题?
我试过这个没有成功:
beforeValidate: function (values, next) {
var req = this.req; // this is undefined
values.createdBy = req.user.id;
next();
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*aer 10
由于请求超出了ORM的范围,我猜测我的方法是错误的,并且我需要将createdBy数据添加到中间件中的req.body.但由于每次请求都没有这样做,我猜想用策略做这件事会更好.像这样:
PostController: {
'*': ['passport', 'sessionAuth'],
create: ['passport', 'sessionAuth',
function (req, res, next) {
if (typeof req.body.createdBy === 'undefined') {
req.body.createdBy = req.user.id;
}
next();
}
]
}
Run Code Online (Sandbox Code Playgroud)
这样我就不需要覆盖蓝图了.
| 归档时间: |
|
| 查看次数: |
3403 次 |
| 最近记录: |