response.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import $ from 'jquery';
  2. import toastr from './toastr';
  3. import isOnline from './offline';
  4. import { config } from 'grav-config';
  5. import trim from 'mout/string/trim';
  6. let UNLOADING = false;
  7. let error = function(response) {
  8. let error = new Error(response.statusText || response || '');
  9. error.response = response;
  10. return error;
  11. };
  12. export function parseStatus(response) {
  13. return response;
  14. /* Whoops can handle JSON responses so we don't need this for now.
  15. if (response.status >= 200 && response.status < 300) {
  16. return response;
  17. } else {
  18. throw error(response);
  19. }
  20. */
  21. }
  22. export function parseJSON(response) {
  23. return response.text().then((text) => {
  24. let parsed = text;
  25. try {
  26. parsed = JSON.parse(text);
  27. } catch (error) {
  28. let content = document.createElement('div');
  29. content.innerHTML = text;
  30. let the_error = new Error();
  31. the_error.stack = trim(content.innerText);
  32. throw the_error;
  33. }
  34. return parsed;
  35. });
  36. }
  37. export function userFeedback(response) {
  38. if (UNLOADING) { return true; }
  39. let status = response.status || (response.error ? 'error' : '');
  40. let message = response.message || (response.error ? response.error.message : null);
  41. let settings = response.toastr || null;
  42. let backup;
  43. switch (status) {
  44. case 'unauthenticated':
  45. document.location.href = config.base_url_relative;
  46. throw error('Logged out');
  47. case 'unauthorized':
  48. status = 'error';
  49. message = message || 'Unauthorized.';
  50. break;
  51. case 'error':
  52. status = 'error';
  53. message = message || 'Unknown error.';
  54. break;
  55. case 'success':
  56. status = 'success';
  57. message = message || '';
  58. break;
  59. default:
  60. status = 'error';
  61. message = message || 'Invalid AJAX response.';
  62. break;
  63. }
  64. if (settings) {
  65. backup = Object.assign({}, toastr.options);
  66. Object.keys(settings).forEach((key) => { toastr.options[key] = settings[key]; });
  67. }
  68. if (message && (isOnline || (!isOnline && status !== 'error'))) {
  69. toastr[status === 'success' ? 'success' : 'error'](message);
  70. }
  71. if (settings) {
  72. toastr.options = backup;
  73. }
  74. return response;
  75. }
  76. export function userFeedbackError(error) {
  77. if (UNLOADING) { return true; }
  78. let stack = error.stack ? `<pre><code>${error.stack}</code></pre>` : '';
  79. toastr.error(`Fetch Failed: <br /> ${error.message} ${stack}`);
  80. console.error(`${error.message} at ${error.stack}`);
  81. }
  82. $(global).on('beforeunload._ajax', () => {
  83. UNLOADING = true;
  84. });