从beforeSave模型挂钩访问请求标头 [英] Access request headers from beforeSave Model Hook
本文介绍了从beforeSave模型挂钩访问请求标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何访问从模型钩提出请求的用户的详细信息
How can i access the details of the user who raise the request from a Model Hook
Comment.beforeSave = function(next,com) {
//Want to add 2 more properties before saving
com.added_at = new Date();
com.added_by = //How can i set the user id here ??
//In case of a Remote hook i have ctx in param and i can get user id like this ctx.req.accessToken.userId; But in Model Hook how can i do the same?
next();
};
有没有办法做到这一点?我用
Is there any way to do this? I tried with Remote hook for main Item in the way
MainItem.beforeRemote('**', function(ctx, user, next) {
if(ctx.methodString == 'leave_request.prototype.__create__comments'){
ctx.req.body.added_by = ctx.req.accessToken.userId;
ctx.req.body.added_at = new Date();
console.log("Added headers as .."+ctx.req.body.added_by);
}
else{
ctx.req.body.requested_at = new Date();
ctx.req.body.requested_by = ctx.req.accessToken.userId;
console.log("Added header @ else as .."+ctx.req.body.requested_by);
}
next();
});
一旦我从资源管理器发出请求,我就可以正确获取控制台日志,但是资源管理器总是向我返回错误
And i get the console logs properly once i make request from explorer , but But the explorer always return me the error
"error": {
"name": "ValidationError",
"status": 422,
"message": "The `comment` instance is not valid. Details: `added_by` can't be blank; `added_at` can't be blank.",
"statusCode": 422,
"details": {
"context": "comment",
"codes": {
"added_by": [
"presence"
],
"added_at": [
"presence"
]
},
"messages": {
"added_by": [
"can't be blank"
],
"added_at": [
"can't be blank"
]
}
},
"stack": "ValidationError: The `comment` instance is not valid. Details: `added_by` can't be blank; `added_at` can't be blank.\n "
}
}
我的模特就像
"properties": {
"body": {
"type": "string",
"required": true
},
"added_by": {
"type": "number",
"required": true
},
"added_at": {
"type": "date",
"required": true
},
"leave_request_id":{
"type": "number",
"required": true
}
}
推荐答案
似乎您无法仅通过覆盖ctx.req.body
来更新相关模型.而不是您应该覆盖ctx.args.data
-似乎使用此ctx参数来初始化相关模型.
It seems that you can't update related model with simply overriding ctx.req.body
. Instead of you should override ctx.args.data
- it looks like this ctx parameter is used to initalize the related model.
所以看起来像这样:
MainItem.beforeRemote('**', function(ctx, user, next) {
if(ctx.methodString == 'leave_request.prototype.__create__comments'){
ctx.args.data.added_by = ctx.req.accessToken.userId;
ctx.args.data.added_at = new Date();
console.log("Added headers as .."+ctx.args.data.added_by);
}
else{ ... }
next();
这篇关于从beforeSave模型挂钩访问请求标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文