Skip to content

Commit

Permalink
Merge pull request #13 from sematext/ssu_SC-12316_dont_drop_request_body
Browse files Browse the repository at this point in the history
SC-12316 read request body asynchronously
  • Loading branch information
ssuvalija authored Oct 14, 2021
2 parents 11a1d1f + fc25831 commit d74fdbd
Showing 1 changed file with 24 additions and 20 deletions.
44 changes: 24 additions & 20 deletions src/ajax/fetch.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* @flow */
import { createListeners } from './listeners';
import { taintUrl, isUrlIgnored } from './common';
import { logDebug } from '../common';

export default function patchFetch(scopeObject: any, ignoreList: string[]) {
const { fetch } = scopeObject;
Expand All @@ -19,39 +20,42 @@ export default function patchFetch(scopeObject: any, ignoreList: string[]) {
redirect,
referrer,
referrerPolicy,
body,
} = request;

const ignored = isUrlIgnored(request.url, ignoreList);
if (ignored) {
// if the request is ignored try sending the original one if possible
return (urlOrRequest && urlOrRequest.url) ?
fetch(urlOrRequest, ...args) : fetch(request, ...args);
fetch(new Request(urlOrRequest), ...args) : fetch(request, ...args);
}

const listeners = createListeners(request.url);
listeners.forEach(l => l.onSend && l.onSend(l));

// Create new request with tainted URL so we can easily find it in performance entries
const { url, taint } = taintUrl(request.url);
const newRequest = new Request(url, {
cache,
credentials,
headers,
integrity,
method,
mode,
redirect,
referrer,
referrerPolicy,
body,
});

const promise = fetch(newRequest, ...args);

promise.then(res =>
listeners.forEach(l => l.onLoadEnd && l.onLoadEnd(l, taint, res.status)));

return promise;
// Request body is fetched asynchronously
return request.blob().then((body) => {
const newRequest = new Request(url, {
cache,
credentials,
headers,
integrity,
method,
mode,
redirect,
referrer,
referrerPolicy,
body: method.toLowerCase() === 'get' || method.toLowerCase() === 'head' ? undefined : body,
});

const promise = fetch(newRequest, ...args);
promise.then(res =>
listeners.forEach(l => l.onLoadEnd && l.onLoadEnd(l, taint, res.status)));
return promise;
}).catch((error) => {
logDebug('Can/\t read request body', error);
});
};
}

0 comments on commit d74fdbd

Please sign in to comment.