Access request headers from a previously simulated model hook

How can I access the details of a user who raises a query using 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 using Remote hook for the main element in the path.

 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 console logs correctly as soon as I make a request from Explorer, but Explorer always returns me an error

"error": {"name": "ValidationError", "status": 422, "message": "The comment instance is not valid. Details: added_by cannot be empty, added_at cannot be empty.", "statusCode": 422, "Details": {"context": "comment", "codes": {"Added": ["presence"], "added_at": ["presence"]}, "Messages": {"Added": [" cannot be empty "]," added_at ": [" cannot be empty "]}}," stack ":" ValidationError: comment instance is invalid. Details: added_by cannot be empty, added_at cannot be empty. \ n " }}

and my model is like

  "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 } 

}

+7
loopbackjs strongloop
source share
5 answers

It seems that you cannot update the associated model with just overriding ctx.req.body . Instead of overriding ctx.args.data - it looks like this ctx parameter is used to initialize the associated model.

So it will look like this:

 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(); 
+9
source share

BeforeRemote hooks are executed before the model hooks, so you can add userId to the request body.

 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(); }); 

You may need to consider which method is best for you.

+2
source share

Faced with the same problem, I used node expiremantal domain (designed to handle errors).

Saving the incoming request object:

 // -- 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); }); 

In the following internal schema, you have access to the req object that is created for each connection:

 process.domain.req 

The StrongLoop team also added context distribution (based on continuation-local-storage ), but it has not yet been documented.

+1
source share

I solved this by adding middleware to parse the body. In middleware.js, I wrote the following code:

 ... "parse": { "body-parser#json": {}, "body-parser#urlencoded": {"params": { "extended": true }} }, ... 

Also, in server.js, I added a requirement for the body parser and the 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 ... 

Then add the dependencies in package.json

 "body-parser": "^1.12.4", "multer": "^0.1.8" 

Now you can do something like: /models/user.js (for any model)

  user.beforeRemote('create', function(ctx, unused, next) { console.log("The registered user is: " + ctx.req.body.email); next(); }); 

Hope this helps! :)

+1
source share

If we assume that there is a comment from the user comments → Comment, you can also try the POST /users/{user_id}/comments relationship method, which will populate foreignId (which can be added_by).

One more thing added_at. As far as I understand, the check hook starts before the hook is created. This means that the verification will not be completed, since this field is marked as required in the model. The question is whether this field should be marked as necessary, because it is set by the server and does not need to be installed by the client API.

0
source share

All Articles