algolia / faux-jax

NO MORE MAINTAINED: Intercept and respond to requests in the browser (AJAX) and Node.js (http(s) module)
MIT License
95 stars 10 forks source link

Feature Request - request.continue() #12

Open kumavis opened 8 years ago

kumavis commented 8 years ago

I only want to intercept requests that match a certain pattern. If the requests don't match the pattern it would be nice to have an easy way to get the request to continue normally.

kumavis commented 8 years ago

this is what i ended up doing to recreate the request

function continueRequestNormally(req){
  var xhr = new XHR()
  // set target url and method
  xhr.open(req.requestMethod, req.requestURL, req.async)
  // set headers
  Object.keys(req.requestHeaders || {}).forEach(function(headerKey){
    xhr.setRequestHeader(headerKey, req.requestHeaders[headerKey])
  })
  // send and call completion handler
  if (req.async) {
    xhr.onload = copyResult
    xhr.send(req.requestBody)
  } else {
    xhr.send(req.requestBody)
    copyResult()
  }

  function copyResult() {
    var headers = extractResponseHeaders(xhr.getAllResponseHeaders())
    req.respond(xhr.status, headers, xhr.response)
  }
}

function extractResponseHeaders(rawHeaders){
  var headers = {}
  var headerKeyValues = rawHeaders.split('\r\n').filter(Boolean)
  headerKeyValues.forEach(function(keyValue){
    var data = keyValue.split(': ')
    headers[data[0]] = data[1]
  })
  return headers
}
vvo commented 8 years ago

I would be happy to take a PR that adds a request.continue(), seems legit

vvo commented 8 years ago

Ultimately I guess we should avoid adding any non-standard methods to XMLHttpRequest, we'd rather add the methods to for example fauxJax.respond(req, ..) but that's maybe extra work. And would require refactoring also/documentation.

Tell me what you think, I would be happy to have you as a new contributor :)

kumavis commented 8 years ago

yeah i think something like fauxJax.performRequest(req) makes the most sense. but yeah tests and doc and stuff...

vvo commented 8 years ago

So yes would take a PR that adds request.continue, for now

kumavis commented 8 years ago

do you have some utility already that does extractResponseHeaders to spec? maybe you only move in the other direction. I just threw this together without tests...

ponelat commented 8 years ago

Huge :+1:

Although, this might be more challenging for a universal ™ solution.

I tried to add a bypass method to https://github.com/moll/node-mitm , but got stuck after I couldn't access some of the requests details. mitm has it only in the socket layer.... I need to buff up on some more of node's http(s) libs to get a better grasp.