greim/hoxy

How to get request json on phase: 'response' ? (to responde conditionally something based on the sent data)

Closed this issue · 9 comments

Hi, I'm struggling on how to get the request body:

proxy.intercept({
  phase: 'response'
}, function(req, resp) {
  var requestHash = {
    url: req.url,
    method: req.method,
    headers: req.headers,
    body: req.json // <- wont work, eithe req.body
  };
  console.log('======================== REQ');
  console.log(req);
  console.log('======================== REQ HASH');
  console.log(requestHash);
  resp.json = {
    happy: 'to be with you'
  };
});

Never mind, i've read this and answered my self
http://greim.github.io/hoxy/#request-json

Okey !!!
I've seen that the .JSON only works with 'request' phase. So how could I respond selectively different data based on a condition that uses the body (req.json) ?

Yup, I've edited the title so it's more accurate.

greim commented

If I understand the question, you'd just use if (req.json.something...) somewhere in the intercept handler.

Because I need the servers answer. I'm trying:
a) to extend servers API. For example, if req.json.extend === true then _.assign(resp.json, { more: true })
so i can finally ) When incoming request, answer a stored (in mongo) version of it ( aka cached ), then continue the request so I can update that stored value with the newest server response

_.assign is the new alias for old _.extend in lodash.

proxy.intercept({
  phase: 'request',
  as: 'json'
}, function(req, resp) {
  var a;
  var requestHash = {
    url: req.url,
    method: req.method,
    headers: req.headers,
    body: req.json
  };
  _.assign(resp.json, {extende: true}); // <- Response isn't being extende, on this phase
  console.log('Check for JSON -> ', req.json.nickname);
  console.log('Respond default extende ->', resp.json);
});

proxy.intercept({
  phase: 'response',
  as: 'json'
}, function(req, resp) {
  var a;
  var requestHash = {
    url: req.url,
    method: req.method,
    headers: req.headers,
    body: req.json
  };
  // _.assign(resp.json, {extende: true}); // <- Response here does extends here, but I've got undefined on req.json
  console.log('Store the value of original -> ', req.json.nickname);
  console.log('With this data, not extended', resp.json);
});
greim commented

You could assign response.json = { ... } during the request phase, but be warned it will suppress the call to the server. http://greim.github.io/hoxy/#response-population

If that isn't what you want, check out this: http://greim.github.io/hoxy/#cycle-data

It would allow you to pass a value from the request to the response cycle which should get you where you need.

Thanks !! I'll give it a try, and tell you later ;)

That did the trick !!! Thanks a lot !!!!