OMGUtils.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. export const fetchHeaders = Object.freeze({
  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. * Creates an abortable AJAX request.
  11. *
  12. * @param {string} url Request endpoint.
  13. * @param {RequestInit} options Fetch options.
  14. * @returns {{fetchPromise: () => Promise<unknown>, abort: () => void}} Request controls.
  15. * @sideEffects Starts a network request.
  16. */
  17. export function AjaxReq(url, options = {}) {
  18. const controller = new AbortController();
  19. const headers = { ...fetchHeaders, ...options.headers };
  20. if (options.body instanceof FormData) {
  21. delete headers['Content-Type'];
  22. }
  23. const requestOptions = { ...options, headers, signal: controller.signal };
  24. const fetchPromise = fetch(url, requestOptions).then(parseJsonResponse);
  25. return {
  26. fetchPromise: () => fetchPromise,
  27. abort: () => controller.abort(),
  28. };
  29. }
  30. /**
  31. * Returns the JSON body of a successful HTTP response.
  32. *
  33. * @param {Response} response Fetch response.
  34. * @returns {Promise<unknown>} Parsed response body.
  35. * @throws {Response} When the response status is not successful.
  36. */
  37. function parseJsonResponse(response) {
  38. if (!response.ok) {
  39. return Promise.reject(response);
  40. }
  41. return response.json();
  42. }