UNPKG

eventbrite

Version:
181 lines (154 loc) 7.02 kB
(function (global, factory) { if (typeof define === "function" && define.amd) { define(["exports", "isomorphic-fetch"], factory); } else if (typeof exports !== "undefined") { factory(exports, require("isomorphic-fetch")); } else { var mod = { exports: {} }; factory(mod.exports, global.fetch); global.request = mod.exports; } })(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (_exports, _isomorphicFetch) { "use strict"; Object.defineProperty(_exports, "__esModule", { value: true }); _exports["default"] = void 0; function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } /** * Return a promise that is resolved or rejected depending on the response's * status code. */ var _checkStatus = function _checkStatus(res) { if (res.status >= 400) { // Need to wrap the response in an object so that it matches the same error object // returned by _catchStatusError return Promise.reject(res); } return Promise.resolve(res); }; var _tryParseJSON = function _tryParseJSON(res) { try { return res.json() // if JSON cannot parse, it'll return a rejected promise instead // of throwing an error, so we catch that rejection so that we can rejected // with the response like everything else expects ["catch"](function () { return Promise.reject(res); }); } catch (error) { return Promise.reject(res); } }; /** * Calls fetch on provided url with default options necessary for interacting * with our JSON API. Parses the JSON, provides appropriate headers, and asserts * a valid status from the server. */ var _fetchJSON = function _fetchJSON(url) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _ref$headers = _ref.headers, headers = _ref$headers === void 0 ? {} : _ref$headers, _ref$method = _ref.method, method = _ref$method === void 0 ? 'GET' : _ref$method, mode = _ref.mode, options = _objectWithoutProperties(_ref, ["headers", "method", "mode"]); var fetchHeaders = headers; if (method !== 'GET') { fetchHeaders = _objectSpread({ 'Content-Type': 'application/json' }, headers); } var fetchOptions = _objectSpread({ method: method, mode: mode, headers: fetchHeaders, credentials: mode === 'cors' ? 'include' : 'same-origin' }, options); return fetch(url, fetchOptions).then(_checkStatus).then(_tryParseJSON); }; var _hasArgumentsError = function _hasArgumentsError(responseData) { return !!(responseData['error_detail'] && responseData['error_detail']['ARGUMENTS_ERROR']); }; /** * Parse v3 errors into an array of objects representing the errors returned by * the API. The format of the parsed errors looks like: * * { * status_code: 400, * error: 'ERROR_CODE', * description: 'Description of the error * } * * An ARGUMENTS_ERROR looks like: * * { * error: 'ARGUMENTS_ERROR', * description: 'Some of the fields were invalid or something', * argumentErrors: { * attr1: ['INVALID'], * attr2: ['This field is required'] * } * } * */ var _parseError = function _parseError(responseData) { if (!responseData.error) { // Weird error format, return null return null; } var error = { error: responseData.error, description: responseData['error_description'] }; if (_hasArgumentsError(responseData)) { error = _objectSpread(_objectSpread({}, error), {}, { argumentErrors: responseData['error_detail']['ARGUMENTS_ERROR'] }); } return error; }; /** * Designed to work with `_checkStatus`, or any function that * raises an error on an invalid status. The error raised should have a `response` * property with the original response object. * * Example usage: * * _fetchJSON('/api/v3/test/path', {'body': someData}) * .catch(_catchStatusError) * .then(doSomethingOnSuccess) * .catch(({response, parsedError}) => doSomethingOnError()); */ var _catchStatusError = function _catchStatusError(res) { return new Promise(function (resolve, reject) { _tryParseJSON(res) // handled error, so reject with parsed error data along with response .then(function (responseData) { return reject({ response: res, parsedError: _parseError(responseData) }); }) // Unhandled error ["catch"](function () { return reject({ response: res }); }); }); }; /** * Low-level method that makes fetch requests, returning the response formatted as JSON. * It parses errors from API v3 and throws exceptions with those errors */ var jsonRequest = function jsonRequest(url, options) { return _fetchJSON(url, options)["catch"](_catchStatusError); }; var _default = jsonRequest; _exports["default"] = _default; }); //# sourceMappingURL=request.js.map