Sonarr/frontend/src/Utilities/createAjaxRequest.js

67 lines
1.5 KiB
JavaScript
Raw Normal View History

2018-01-13 02:01:27 +00:00
import $ from 'jquery';
2019-03-03 19:29:12 +00:00
const absUrlRegex = /^(https?:)?\/\//i;
const apiRoot = window.Sonarr.apiRoot;
function isRelative(ajaxOptions) {
return !absUrlRegex.test(ajaxOptions.url);
}
function moveBodyToQuery(ajaxOptions) {
if (ajaxOptions.data && ajaxOptions.type === 'DELETE') {
if (ajaxOptions.url.contains('?')) {
ajaxOptions.url += '&';
} else {
ajaxOptions.url += '?';
}
ajaxOptions.url += $.param(ajaxOptions.data);
delete ajaxOptions.data;
}
}
function addRootUrl(ajaxOptions) {
ajaxOptions.url = apiRoot + ajaxOptions.url;
}
function addApiKey(ajaxOptions) {
ajaxOptions.headers = ajaxOptions.headers || {};
ajaxOptions.headers['X-Api-Key'] = window.Sonarr.apiKey;
}
export default function createAjaxRequest(originalAjaxOptions) {
2018-01-13 02:01:27 +00:00
const requestXHR = new window.XMLHttpRequest();
let aborted = false;
let complete = false;
function abortRequest() {
if (!complete) {
aborted = true;
requestXHR.abort();
}
}
2019-08-28 21:43:55 +00:00
const ajaxOptions = { dataType: 'json', ...originalAjaxOptions };
2019-03-03 19:29:12 +00:00
if (isRelative(ajaxOptions)) {
moveBodyToQuery(ajaxOptions);
addRootUrl(ajaxOptions);
addApiKey(ajaxOptions);
}
2018-01-13 02:01:27 +00:00
const request = $.ajax({
xhr: () => requestXHR,
...ajaxOptions
}).then(null, (xhr, textStatus, errorThrown) => {
xhr.aborted = aborted;
return $.Deferred().reject(xhr, textStatus, errorThrown).promise();
}).always(() => {
complete = true;
});
return {
request,
abortRequest
};
}