fetchJSON.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports["default"] = void 0;
  6. var _merge = _interopRequireDefault(require("lodash/merge"));
  7. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  8. /* global fetch */
  9. var fetchJSON = function fetchJSON(url) {
  10. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  11. // The Content-Type header describes the type of the body so should be
  12. // omitted when there isn't one.
  13. var fetchOptions = typeof options.body === 'undefined' ? options : (0, _merge["default"])({
  14. headers: {
  15. 'Content-Type': 'application/json'
  16. }
  17. }, options);
  18. return fetch(url, fetchOptions).then(function (response) {
  19. return getResponseBody(response).then(function (body) {
  20. return {
  21. response: response,
  22. body: body
  23. };
  24. });
  25. }).then(checkStatus);
  26. };
  27. var getResponseBody = function getResponseBody(response) {
  28. var contentType = response.headers.get('content-type');
  29. return contentType && contentType.indexOf('json') >= 0 ? response.clone().text().then(tryParseJSON) : response.clone().text();
  30. };
  31. var tryParseJSON = function tryParseJSON(json) {
  32. if (!json) {
  33. return null;
  34. }
  35. try {
  36. return JSON.parse(json);
  37. } catch (e) {
  38. throw new Error("Failed to parse unexpected JSON response: ".concat(json));
  39. }
  40. };
  41. function ResponseError(status, response, body) {
  42. this.name = 'ResponseError';
  43. this.status = status;
  44. this.response = response;
  45. this.body = body;
  46. } // $FlowIssue
  47. ResponseError.prototype = Error.prototype;
  48. var checkStatus = function checkStatus(_ref) {
  49. var response = _ref.response,
  50. body = _ref.body;
  51. if (response.ok) {
  52. return {
  53. response: response,
  54. body: body
  55. };
  56. } else {
  57. throw new ResponseError(response.status, response, body);
  58. }
  59. };
  60. var _default = fetchJSON;
  61. exports["default"] = _default;