OMGUtils.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. const fetchHeaders = {
  2. 'Accept': 'text/html',
  3. 'Content-Type': 'text/html',
  4. 'X-Requested-With': 'XMLHttpRequest',
  5. 'Cache-Control': 'no-cache',
  6. 'Pragma': 'no-cache',
  7. 'Expires': '0'
  8. };
  9. /**
  10. * Make an AJAX request.
  11. *
  12. * If error, catch return a promise error object:
  13. *
  14. * .catch(err => alert(`${err.url}\n\n${err.status} (${err.statusText})`));
  15. *
  16. * @param url URL of RESTful api to call
  17. * @param options the fetch() options
  18. * @param complete Promise resolve callback
  19. * @param error Promise reject callback
  20. * @returns Object {Promise, signal: AbortController}
  21. */
  22. export function AjaxReq(url, options, complete, error) {
  23. let fetchSignal = new AbortController();
  24. let defaults = {
  25. headers: fetchHeaders,
  26. signal: fetchSignal.signal
  27. };
  28. // Extend default options
  29. Object.assign(defaults, options);
  30. let fetchPromise = fetch(url, defaults)
  31. .then(resp => {
  32. if (resp.status === 200)
  33. return resp.json();
  34. else
  35. return Promise.reject(resp);
  36. })
  37. .catch(err => {
  38. if (err.name === 'AbortError')
  39. return;
  40. if (err.url !== undefined)
  41. toastr.error(err.url, `${err.status} (${err.statusText})`);
  42. else
  43. toastr.error(err);
  44. });
  45. // Add some properties to return value
  46. return {
  47. fetchPromise: () => fetchPromise,
  48. abort: function () {
  49. fetchSignal.abort()
  50. }
  51. };
  52. }