doc.yeswiki.pro/node_modules/@algolia/requester-browser-xhr/dist/requester-browser-xhr.cjs.js

62 lines
2.7 KiB
JavaScript
Raw Normal View History

2023-05-20 16:37:42 +00:00
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function createBrowserXhrRequester() {
return {
send(request) {
return new Promise((resolve) => {
const baseRequester = new XMLHttpRequest();
baseRequester.open(request.method, request.url, true);
Object.keys(request.headers).forEach(key => baseRequester.setRequestHeader(key, request.headers[key]));
const createTimeout = (timeout, content) => {
return setTimeout(() => {
baseRequester.abort();
resolve({
status: 0,
content,
isTimedOut: true,
});
}, timeout * 1000);
};
const connectTimeout = createTimeout(request.connectTimeout, 'Connection timeout');
// eslint-disable-next-line functional/no-let
let responseTimeout;
// eslint-disable-next-line functional/immutable-data
baseRequester.onreadystatechange = () => {
if (baseRequester.readyState > baseRequester.OPENED && responseTimeout === undefined) {
clearTimeout(connectTimeout);
responseTimeout = createTimeout(request.responseTimeout, 'Socket timeout');
}
};
// eslint-disable-next-line functional/immutable-data
baseRequester.onerror = () => {
// istanbul ignore next
if (baseRequester.status === 0) {
clearTimeout(connectTimeout);
clearTimeout(responseTimeout);
resolve({
content: baseRequester.responseText || 'Network request failed',
status: baseRequester.status,
isTimedOut: false,
});
}
};
// eslint-disable-next-line functional/immutable-data
baseRequester.onload = () => {
clearTimeout(connectTimeout);
clearTimeout(responseTimeout);
resolve({
content: baseRequester.responseText,
status: baseRequester.status,
isTimedOut: false,
});
};
baseRequester.send(request.data);
});
},
};
}
exports.createBrowserXhrRequester = createBrowserXhrRequester;