javascript: make utils.ajax() return a promise

This allow to use `await ajax(…)`, and still have Rails manage the
request, insert the proper headers and tokens, etc.
This commit is contained in:
Pierre de La Morinerie 2020-03-16 19:19:50 +01:00
parent 0c944ceeb2
commit ec2199f7b1

View file

@ -3,7 +3,7 @@ import $ from 'jquery';
import debounce from 'debounce';
export { debounce };
export const { fire, ajax } = Rails;
export const { fire } = Rails;
export function show(el) {
el && el.classList.remove('hidden');
@ -45,6 +45,22 @@ export function delegate(eventNames, selector, callback) {
);
}
export function ajax(options) {
return new Promise((resolve, reject) => {
Object.assign(options, {
success: (response, statusText, xhr) => {
resolve({ response, statusText, xhr });
},
error: (response, statusText, xhr) => {
let error = new Error(`Erreur ${xhr.status} : ${statusText}`);
Object.assign(error, { response, statusText, xhr });
reject(error);
}
});
Rails.ajax(options);
});
}
export function getJSON(url, data, method = 'get') {
incrementActiveRequestsCount();
data = method !== 'get' ? JSON.stringify(data) : data;