Skip to content

Commit

Permalink
Attempt to add request/response heaers
Browse files Browse the repository at this point in the history
  • Loading branch information
rezgar committed Dec 12, 2023
1 parent 029b0b5 commit 3d014a5
Showing 1 changed file with 44 additions and 15 deletions.
59 changes: 44 additions & 15 deletions lib/xhr-proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,20 +49,30 @@ function XMLHttpRequestProxy() {

var method_ = null;
var url_ = null;
var requestHeaders_ = null;
var shouldAddToCache_ = false;

var self = this;

// Facade the status, statusText and response properties to spec XMLHttpRequest
this.status = 0; // This is the status if error due to browser offline, etc.
this.statusText = "";
this.response = "";
this.responseText = "";
this.responseHeaders = undefined;
// Facade the onload, onreadystatechange to spec XMLHttpRequest
this.onreadystatechange = null;
this.onload = null;

Object.defineProperty(self, 'proxymethod', { get: function() {return method_;} });
Object.defineProperty(self, 'proxyurl', { get: function() {return url_;} });
Object.defineProperty(self, 'response', { get: function() {
switch(self.responseHeaders['content-type']) {
case 'json':
return JSON.parse(self.responseText);
default:
return self.responseText;
}
} });

function shouldCache(method, url) {
if (_.isFunction(cacheSelector)) { return cacheSelector.call(self, method, url); }
Expand All @@ -85,16 +95,26 @@ function XMLHttpRequestProxy() {
if (options.debugEvents) console.log('[Teuthis] proxy-xhr-onload ' + xhr.status + ' ' + xhr.statusText);
self.status = xhr.status;
self.statusText = xhr.statusText;
self.response = xhr.response;
if (xhr.status >= 200 && xhr.status < 300 && xhr.response) {
self.responseText = xhr.responseText;
self.responseHeaders = xhr.getAllResponseHeaders();
if (self.responseHeaders) {
self.responseHeaders = self.responseHeaders.trim().split('\r\n').reduce((acc, current) => {
const [x,v] = current.split(': ');
return Object.assign(acc, { [x.toLowerCase()] : v });
}, {});
}
else {
self.responseHeaders = {};
}
if (xhr.status >= 200 && xhr.status < 300 && xhr.responseText) {
if (shouldAddToCache_ === true) {
var mangled = cachekeymangler(url_);
if (options.debugEvents) console.log('[Teuthis] proxy-xhr-onload do-put ' + method_ + ' ' + mangled);
// console.log('proxy-cache-type ' + xhr.responseType); // + ', ' + xhr.responseText.substring(0,64));
// if (xhr.responseType === 'arraybuffer')
// Assuming the response is string or arraybuffer then clone it first, otherwise things seem to not work properly
var savedResponse = xhr.response.slice(0);
var cachedResponse = { v: savedResponse, ts: Date.now() };
var savedResponseText = xhr.responseText.slice(0);
var cachedResponse = { v: savedResponseText, ts: Date.now() };

store.put(method_, mangled, cachedResponse, function() {
if (_.isFunction(onloadhook)) { onloadhook(shouldAddToCache_, self, xhr); }
Expand Down Expand Up @@ -122,8 +142,8 @@ function XMLHttpRequestProxy() {
self.statusText = '200 OK';
if (_.isFunction(self.onreadystatechange)) { self.onreadystatechange(); }

if (alternativeResponse.response) {
self.response = alternativeResponse.response;
if (alternativeResponse.responseText) {
self.responseText = alternativeResponse.responseText;
}
self.readyState = 4; // Done
if (_.isFunction(onloadhook)) { onloadhook('on-error', self, xhr); }
Expand All @@ -144,6 +164,15 @@ function XMLHttpRequestProxy() {
xhr.open.apply(xhr, arguments);
};

this.setRequestHeader(name, value) {
if (!this.requestHeaders_) {
this.requestHeaders_ = {};
}
// collect headers
this.requestHeaders_[name] = value;
xhr.setRequestHeader.apply(xhr, arguments);
}

// Facade XMLHttpRequest.send() with a version that queries our offline cache,
// calls the original if the response is not found in the cache, then adds the response to the cache,
// or calls to onload() with the cached response if found
Expand All @@ -164,15 +193,15 @@ function XMLHttpRequestProxy() {
// miss - not in our cache. So try and fetch from the real Internet
//console.log('onMiss called'); console.log(arguments);
if (_.isFunction(onmisshook)) {
var res = {url: url_, status: +200, statusText: '200 OK', response: undefined, readyState: 4};
var res = {url: url_, status: +200, statusText: '200 OK', responseText: undefined, readyState: 4};
var patch = onmisshook(self, xhr, res);
if (patch) {
// Miss hook returns undefined, or otherwise, a replacement response,
// and it should fix self status, statusText, response, and readyState
self.status = res.status;
self.statusText = res.statusText;
if (_.isFunction(self.onreadystatechange)) { self.onreadystatechange(); }
self.response = res.response;
self.responseText = res.responseText;
self.readyState = res.readyState;
if (_.isFunction(onloadhook)) { onloadhook('on-match', self, xhr); }
if (_.isFunction(self.onload)) { self.onload(); }
Expand All @@ -189,7 +218,7 @@ function XMLHttpRequestProxy() {
self.status = +200;
self.statusText = '200 OK';
if (_.isFunction(self.onreadystatechange)) { self.onreadystatechange(); }
self.response = cachedValue.v;
self.responseText = cachedValue.v;
self.readyState = 4; // Done
if (_.isFunction(onloadhook)) { onloadhook('on-match', self, xhr); }
if (_.isFunction(self.onload)) { self.onload(); }
Expand All @@ -204,15 +233,15 @@ function XMLHttpRequestProxy() {
// miss - not in our cache. So try and fetch from the real Internet
//console.log('onMiss called'); console.log(arguments);
if (_.isFunction(onmisshook)) {
var res = {url: url_, status: +200, statusText: '200 OK', response: undefined, readyState: 4};
var res = {url: url_, status: +200, statusText: '200 OK', responseText: undefined, readyState: 4};
var patch = onmisshook(self, xhr, res);
if (patch) {
// Miss hook returns undefined, or otherwise, a replacement response,
// and it should fix self status, statusText, response, and readyState
self.status = res.status;
self.statusText = res.statusText;
if (_.isFunction(self.onreadystatechange)) { self.onreadystatechange(); }
self.response = res.response;
self.responseText = res.responseText;
self.readyState = res.readyState;
if (_.isFunction(onloadhook)) { onloadhook('on-match', self, xhr); }
if (_.isFunction(self.onload)) { self.onload(); }
Expand All @@ -228,8 +257,8 @@ function XMLHttpRequestProxy() {
}
};

// facade all other XMLHttpRequest getters, except 'status'
["responseURL", "responseText", "responseXML", "upload"].forEach(function(item) {
// facade all other XMLHttpRequest getters, except 'status' and 'response'
["responseURL", "responseXML", "upload"].forEach(function(item) {
Object.defineProperty(self, item, {
get: function() {return xhr[item];},
});
Expand All @@ -245,7 +274,7 @@ function XMLHttpRequestProxy() {

// facade all pure XMLHttpRequest methods and EVentTarget ancestor methods
["addEventListener", "removeEventListener", "dispatchEvent",
"abort", "getAllResponseHeaders", "getResponseHeader", "overrideMimeType", "setRequestHeader"].forEach(function(item) {
"abort", "getAllResponseHeaders", "getResponseHeader", "overrideMimeType"].forEach(function(item) {
Object.defineProperty(self, item, {
value: function() {return xhr[item].apply(xhr, arguments);},
});
Expand Down

0 comments on commit 3d014a5

Please sign in to comment.