Loopbackjs 从beforeSave模型钩子访问请求头
如何访问从模型挂钩提出请求的用户的详细信息Loopbackjs 从beforeSave模型钩子访问请求头,loopbackjs,strongloop,Loopbackjs,Strongloop,如何访问从模型挂钩提出请求的用户的详细信息 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 ca
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();
};
有没有办法做到这一点?我试着用遥控器钩住挡道的主要部件
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();
}))
一旦我从资源管理器发出请求,我就可以正确地获取控制台日志,但是资源管理器总是返回错误
"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
}
}beforeRemote钩子在模型钩子之前执行,因此您可以将用户ID添加到请求正文中
Comment.beforeRemote('**', function (ctx, unused, next) {
var userId = ctx.req.accessToken.userId;
if (ctx.methodString == 'Comment.create' || ctx.methodString == 'Comment.updateAttributes') {
ctx.req.body.userId = userId;
}
next();
});
您可能想查看哪个methodstring最适合您。面对同样的问题,我使用了node expiremantal功能(用于错误处理) 正在保存传入请求对象:
// -- Your pre-processing middleware here --
app.use(function (req, res, next) {
// create per request domain instance
var domain = require('domain').create();
// save request to domain, to make it accessible everywhere
domain.req = req;
domain.run(next);
});
接下来,在模型钩子中,您可以访问req对象,该对象是根据每个连接创建的:
process.domain.req
此外,StrongLoop团队添加了(基于),但尚未记录。如果我们假设存在用户->注释的关系注释,您也可以尝试使用关系方法
POST/users/{User\u id}/comments
,该方法将填充异化(可通过添加)
另一件事是在。据我所知,验证钩子是在创建钩子之前触发的。这意味着验证将失败,因为此字段在模型中标记为必需。问题是是否应该将此字段标记为必需,因为它是由服务器设置的,而不需要由API的客户端设置。似乎您不能简单地覆盖
ctx.req.body
来更新相关模型。相反,您应该重写ctx.args.data
——看起来此ctx参数用于初始化相关模型
所以看起来是这样的:
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();
我通过添加用于正文解析的中间件解决了这个问题。在middleware.js中,我编写了以下代码:
...
"parse": {
"body-parser#json": {},
"body-parser#urlencoded": {"params": { "extended": true }}
},
...
此外,在server.js中,我添加了对主体解析器和multer的要求:
var loopback = require('loopback');
...
var bodyParser = require('body-parser');
var multer = require('multer');
...
app.use(bodyParser.json()); // application/json
app.use(bodyParser.urlencoded({ extended: true })); // application/x-www-form-urlencoded
app.use(multer()); // multipart/form-data
...
然后在package.json中添加依赖项
"body-parser": "^1.12.4",
"multer": "^0.1.8"
现在,您可以在/models/user.js中执行以下操作(适用于任何模型)
我希望这有帮助!:) 我的评论模型没有直接暴露于api。所以beforemote不会为它执行。我的端点是MainItem//Comment。因此beforeRemote将仅对MainItem执行。在这种情况下,您需要在MainItem模型上设置钩子,并尝试将用户ID存储在全局或注释设置中。这不是最优的,可能会导致并发请求出错。很抱歉。如何获取ctx中操作挂钩的请求正文?
user.beforeRemote('create', function(ctx, unused, next) {
console.log("The registered user is: " + ctx.req.body.email);
next();
});