Skip to content

Commit

Permalink
Replace $.ajax() with fetch()
Browse files Browse the repository at this point in the history
  • Loading branch information
asdil12 and Martchus committed Sep 19, 2024
1 parent 0967772 commit 68bc207
Show file tree
Hide file tree
Showing 7 changed files with 162 additions and 139 deletions.
49 changes: 27 additions & 22 deletions assets/javascripts/admin_assets.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,37 +121,42 @@ function reloadAssetsTable() {
}

function deleteAsset(assetId) {
$.ajax({
url: urlWithBase('/api/v1/assets/' + assetId),
method: 'DELETE',
dataType: 'json',
success: function () {
fetchWithCSRF(urlWithBase(`/api/v1/assets/${assetId}`), {method: 'DELETE'})
.then(response => {
// not checking for status code as 404 case also returns proper json
return response.json();
})
.then(response => {
if (response.error) throw response.error;
addFlash(
'info',
'The asset was deleted successfully. The asset table\'s contents are cached. Hence the removal is not immediately visible. To update the view use the "Trigger asset cleanup" button. Note that this is an expensive operation which might take a while.'
"The asset was deleted successfully. The asset table's contents are cached." +
'Hence the removal is not immediately visible. To update the view use the "Trigger asset cleanup" button.' +
'Note that this is an expensive operation which might take a while.'
);
},
error: function (xhr, ajaxOptions, thrownError) {
var error_message = xhr.responseJSON.error;
addFlash('danger', error_message);
}
});
})
.catch(error => {
console.error(error);
addFlash('danger', `Error deleting asset: ${error}`);
});
}

function triggerAssetCleanup(form) {
$.ajax({
url: form.action,
method: form.method,
success: function () {
fetchWithCSRF(form.action, {method: form.method})
.then(response => {
if (!response.ok) throw `Server returned ${response.status}: ${response.statusText}`;
return response.json();
})
.then(response => {
addFlash(
'info',
'Asset cleanup has been triggered. Open the <a href="/minion/jobs?task=limit_assets">Minion dashboard</a> to keep track of the task.'
`Asset cleanup has been triggered. Open the <a href="/minion/jobs?task=limit_assets">Minion dashboard</a> to keep track of the task (gru_id #${response.gru_id}).`
);
},
error: function (xhr, ajaxOptions, thrownError) {
addFlash('danger', 'Unable to trigger the asset cleanup: ' + thrownError);
}
});
})
.catch(error => {
console.error(error);
addFlash('danger', `Unable to trigger the asset cleanup: ${error}`);
});
}

function showLastAssetStatusUpdate(assetStatus) {
Expand Down
108 changes: 55 additions & 53 deletions assets/javascripts/comments.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,6 @@ function renderCommentHeading(comment, commentId) {
return heading;
}

function showXhrError(context, jqXHR, textStatus, errorThrown) {
window.alert(context + getXhrError(jqXHR, textStatus, errorThrown));
}

function updateNumerOfComments() {
const commentsLink = document.querySelector('a[href="#comments"]');
if (commentsLink) {
Expand All @@ -51,15 +47,15 @@ function deleteComment(deleteButton) {
if (!window.confirm('Do you really want to delete the comment written by ' + author + '?')) {
return;
}
$.ajax({
url: deleteButton.dataset.deleteUrl,
method: 'DELETE',
success: () => {
fetchWithCSRF(deleteButton.dataset.deleteUrl, {method: 'DELETE'})
.then(response => {
if (!response.ok) throw `Server returned ${response.status}: ${response.statusText}`;
$(deleteButton).parents('.comment-row, .pinned-comment-row').remove();
updateNumerOfComments();
},
error: showXhrError.bind(undefined, "The comment couldn't be deleted: ")
});
})
.catch(error => {
window.alert(`The comment couldn't be deleted: ${error}`);
});
}

function updateComment(form) {
Expand All @@ -75,31 +71,30 @@ function updateComment(form) {
displayElements([textElement, form.applyChanges, form.discardChanges], 'none');
markdownElement.style.display = '';
markdownElement.innerHTML = '<em>Loading…</em>';
$.ajax({
url: url,
method: 'PUT',
data: $(form).serialize(),
success: () => {
$.ajax({
url: url,
method: 'GET',
success: response => {
fetchWithCSRF(url, {method: 'PUT', body: new FormData(form)})
.then(response => {
if (!response.ok) throw `Server returned ${response.status}: ${response.statusText}`;
// get rendered markdown
fetch(url)
.then(response => {
if (!response.ok) throw `Server returned ${response.status}: ${response.statusText}`;
return response.json();
})
.then(comment => {
const commentId = headingElement.querySelector('.comment-anchor').href.split('#comment-')[1];
headingElement.replaceWith(renderCommentHeading(response, commentId));
textElement.value = response.text;
markdownElement.innerHTML = response.renderedMarkdown;
headingElement.replaceWith(renderCommentHeading(comment, commentId));
textElement.value = comment.text;
markdownElement.innerHTML = comment.renderedMarkdown;
hideCommentEditor(form);
},
error: () => location.reload()
});
},
error: (jqXHR, textStatus, errorThrown) => {
textElement.value = text;
markdownElement.innerHTML = markdown;
showCommentEditor(form);
window.alert("The comment couldn't be updated: " + getXhrError(jqXHR, textStatus, errorThrown));
}
});
})
.catch(error => {
console.error(error);
location.reload();
});
})
.catch(error => {
window.alert(`The comment couldn't be updated : ${error}`);
});
}

function addComment(form, insertAtBottom) {
Expand All @@ -109,22 +104,26 @@ function addComment(form, insertAtBottom) {
return window.alert("The comment text mustn't be empty.");
}
const url = form.action;
$.ajax({
url: url,
method: 'POST',
data: $(form).serialize(),
success: response => {
const commentId = response.id;
fetch(url, {method: 'POST', body: new FormData(form)})
.then(response => {
if (!response.ok) throw `Server returned ${response.status}: ${response.statusText}`;
return response.json();
})
.then(data => {
const commentId = data.id;
console.log(`Created comment #${commentId}`);
// get rendered markdown
$.ajax({
url: url + '/' + commentId,
method: 'GET',
success: response => {
fetch(`${url}/${commentId}`)
.then(response => {
if (!response.ok) throw `Server returned ${response.status}: ${response.statusText}`;
return response.json();
})
.then(comment => {
const templateElement = document.getElementById('comment-row-template');
const commentRow = $(templateElement.innerHTML.replace(/@comment_id@/g, commentId))[0];
commentRow.querySelector('[name="text"]').value = response.text;
commentRow.querySelector('h4').replaceWith(renderCommentHeading(response, commentId));
commentRow.querySelector('.markdown').innerHTML = response.renderedMarkdown;
commentRow.querySelector('[name="text"]').value = comment.text;
commentRow.querySelector('h4').replaceWith(renderCommentHeading(comment, commentId));
commentRow.querySelector('.markdown').innerHTML = comment.renderedMarkdown;
let nextElement;
if (!insertAtBottom) {
nextElement = document.querySelectorAll('.comment-row')[0];
Expand All @@ -136,12 +135,15 @@ function addComment(form, insertAtBottom) {
$('html, body').animate({scrollTop: commentRow.offsetTop}, 1000);
textElement.value = '';
updateNumerOfComments();
},
error: () => location.reload()
});
},
error: showXhrError.bind(undefined, "The comment couldn't be added: ")
});
})
.catch(error => {
console.error(error);
location.reload();
});
})
.catch(error => {
window.alert(`The comment couldn't be added: ${error}`);
});
}

function insertTemplate(button) {
Expand Down
27 changes: 12 additions & 15 deletions assets/javascripts/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,28 +93,25 @@ function loadBuildResults(queryParams) {
};

// query build results via AJAX using parameters from filter form
$.ajax({
url: buildResultsElement.data('build-results-url'),
data: queryParams ? queryParams : window.location.search.substr(1),
success: function (response) {
showBuildResults(response);
var url = new URL(buildResultsElement.data('build-results-url'), window.location.href);
url.search = queryParams ? queryParams : window.location.search.substr(1);
fetch(url)
.then(response => {
if (!response.ok) throw `Server returned ${response.status}: ${response.statusText}`;
return response.text();
})
.then(responsetext => {
showBuildResults(responsetext);
window.buildResultStatus = 'success';
},
error: function (xhr, textStatus, thrownError) {
// ignore error if just navigating away
if (textStatus !== 'timeout' && !xhr.getAllResponseHeaders()) {
return;
}
const error = xhr.responseJSON?.error;
})
.catch(error => {
const message = error ? htmlEscape(error) : 'Unable to fetch build results.';
showBuildResults(
'<div class="alert alert-danger" role="alert">' +
message +
'<a href="javascript:loadBuildResults();" style="float: right;">Try again</a></div>'
);
window.buildResultStatus = 'error: ' + thrownError;
}
});
});
}

function autoRefreshRestart() {
Expand Down
32 changes: 21 additions & 11 deletions assets/javascripts/openqa.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ function setupForAll() {
});
}

function getCSRFToken() {
return document.querySelector('meta[name="csrf-token"]').content;
}

function fetchWithCSRF(resource, options) {
options.headers ??= {};
options.headers['X-CSRF-TOKEN'] ??= getCSRFToken();
return fetch(resource, options);
}

function makeFlashElement(text) {
return typeof text === 'string' ? '<span>' + text + '</span>' : text;
}
Expand Down Expand Up @@ -238,11 +248,12 @@ function restartJob(ajaxUrl, jobId) {
addFlash('danger', errorMessage);
};

return $.ajax({
type: 'POST',
url: ajaxUrl,
success: function (data, res, xhr) {
var responseJSON = xhr.responseJSON;
return fetchWithCSRF(ajaxUrl, {method: 'POST'})
.then(response => {
if (!response.ok) throw `Server returned ${response.status}: ${response.statusText}`;
return response.json();
})
.then(responseJSON => {
var newJobUrl;
try {
newJobUrl = responseJSON.test_url[0][jobId];
Expand All @@ -261,13 +272,12 @@ function restartJob(ajaxUrl, jobId) {
if (newJobUrl) {
window.location.replace(newJobUrl);
} else {
showError('URL for new job not available');
throw 'URL for new job not available';
}
},
error: function (xhr, ajaxOptions, thrownError) {
showError(xhr.responseJSON ? xhr.responseJSON.error : undefined);
}
});
})
.catch(error => {
showError(error);
});
}

function htmlEscape(str) {
Expand Down
17 changes: 7 additions & 10 deletions assets/javascripts/overview.js
Original file line number Diff line number Diff line change
Expand Up @@ -301,20 +301,17 @@ function addComments(form) {
controls.style.display = 'inline';
window.addCommentsModal.hide();
};
$.ajax({
url: form.action,
method: 'POST',
data: $(form).serialize(),
success: response => {
fetchWithCSRF(form.action, {method: 'POST', body: new FormData(form)})
.then(response => {
if (!response.ok) throw `Server returned ${response.status}: ${response.statusText}`;
addFlash(
'info',
'The comments have been created. <a href="javascript: location.reload()">Reload</a> the page to show changes.'
);
done();
},
error: (jqXHR, textStatus, errorThrown) => {
addFlash('danger', 'The comments could not be added: ' + getXhrError(jqXHR, textStatus, errorThrown));
})
.catch(error => {
addFlash('danger', `The comments could not be added: ${error}`);
done();
}
});
});
}
Loading

0 comments on commit 68bc207

Please sign in to comment.