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 addRootUrl(ajaxOptions) {
|
|
|
|
ajaxOptions.url = apiRoot + ajaxOptions.url;
|
|
|
|
}
|
|
|
|
|
|
|
|
function addApiKey(ajaxOptions) {
|
|
|
|
ajaxOptions.headers = ajaxOptions.headers || {};
|
|
|
|
ajaxOptions.headers['X-Api-Key'] = window.Sonarr.apiKey;
|
|
|
|
}
|
|
|
|
|
2021-02-07 03:28:33 +00:00
|
|
|
function addContentType(ajaxOptions) {
|
|
|
|
if (
|
2021-02-08 16:21:14 +00:00
|
|
|
ajaxOptions.contentType == null &&
|
2021-02-07 03:28:33 +00:00
|
|
|
ajaxOptions.dataType === 'json' &&
|
2021-11-06 20:44:26 +00:00
|
|
|
(ajaxOptions.method === 'PUT' || ajaxOptions.method === 'POST' || ajaxOptions.method === 'DELETE')) {
|
2021-02-07 03:28:33 +00:00
|
|
|
ajaxOptions.contentType = 'application/json';
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-03 19:29:12 +00:00
|
|
|
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();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-06 20:44:26 +00:00
|
|
|
const ajaxOptions = { ...originalAjaxOptions };
|
2019-03-03 19:29:12 +00:00
|
|
|
|
|
|
|
if (isRelative(ajaxOptions)) {
|
|
|
|
addRootUrl(ajaxOptions);
|
|
|
|
addApiKey(ajaxOptions);
|
2021-02-07 03:28:33 +00:00
|
|
|
addContentType(ajaxOptions);
|
2019-03-03 19:29:12 +00:00
|
|
|
}
|
|
|
|
|
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
|
|
|
|
};
|
|
|
|
}
|