At what point of the request lifecycle do `req.options` & `req.options.blueprintAction` get "added"?

31 views
Skip to first unread message

Aziz Khoury

unread,
Dec 21, 2017, 7:31:28 AM12/21/17
to sails.js
Hi all,

I created a middleware that adds X-Total-Count header to the find blueprint actions by default, it works with a workaround and I would like to avoid that workaround.

My issue is that I don't know when, during the lifecycle of the request, the req.options and the req.options.blueprintAction get added to the req object. 


Main Question: Is there a best-practice or neat way to add a middleware that gets executed after sails has parsed the request? 

I was able to achieve this, but only after I overwritten the res.send function (see the third test below)


# First test using http middleware in config/http.js

If I use the usual way to add a middleware to a sails app, then make a "blueprint" request, req.options is still undefined by the time my middleware is called.

order: [
  // ... 
  'myRequestLogger'
  // ...
],

myRequestLogger: function (req, res, next) { 
    console.log("req.options", req.options); // prints: req.options undefined
    return next(); 
}

# Second test using policies

If I add a policy: api/policies/mustLog.js, then make a "blueprint" request, req.options is defined, but req.options.blueprintAction is not

module.exports = (req, res, next) => {
    req.options && console.log("req.options.action", req.options.action); // prints :model/:action
    req.options && console.log("req.options.blueprintAction", req.options.blueprintAction);  // prints undefined
    next();
};

Then in config/policies.js

'*': ['mustLog']

# Third test using res.send override

Back to config/http.js but this time instead of calling the middleware immediately, the middleware will basically override res.send which will cause our logging code block to execute lastly, right before it goes over over the wire.

This worksreq.options.blueprintAction is there when I make a "blueprint" request, but I really don't want  to override res.send.

order: [
  // ... 
  'myRequestLogger'
  // ...
],

myRequestLogger: function (req, res, next) {    
    let oldSend = res.send;
    res.send = function () {       
       req.options && console.log("req.options.action", req.options.action); // prints :model/:action
       req.options && console.log("req.options.blueprintAction", req.options.blueprintAction);  // prints :action       
       return oldSend.apply(res, arguments);
    };
     
    next(); 
}

Thanks a lot

Reply all
Reply to author
Forward
0 new messages