OMGUtils.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. export 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. * @returns Object {Promise, signal: AbortController}
  19. */
  20. export function AjaxReq(url, options) {
  21. let fetchSignal = new AbortController();
  22. let defaults = {
  23. headers: fetchHeaders,
  24. signal: fetchSignal.signal
  25. };
  26. // Extend default options
  27. Object.assign(defaults, options);
  28. let fetchPromise = fetch(url, defaults)
  29. .then(resp => {
  30. if (resp.status === 200)
  31. return resp.json();
  32. else
  33. return Promise.reject(resp);
  34. })
  35. .catch(err => {
  36. if (err.name === 'AbortError')
  37. return;
  38. if (err.url !== undefined)
  39. toastr.error(err.url, `${err.status} (${err.statusText})`);
  40. else
  41. toastr.error(err);
  42. });
  43. // Add some properties to return value
  44. return {
  45. fetchPromise: () => fetchPromise,
  46. abort: function () {
  47. fetchSignal.abort()
  48. }
  49. };
  50. }