OMGUtils.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. * @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. // Add some properties to return value
  36. let ret = {};
  37. Object.assign(ret, {
  38. fetchPromise: () => fetchPromise,
  39. abort: function () {
  40. fetchSignal.abort()
  41. }
  42. });
  43. return ret;
  44. }