UNPKG

@appzmonster/fetch-interceptor

Version:

Fetch-interceptor is a JavaScript library to enable request interceptor feature on Fetch API. The library extends Fetch API and uses fluent API design to allow chaining of one or multiple request interceptors to a Fetch API request.

215 lines (161 loc) 9.34 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _BaseInterceptor2 = _interopRequireDefault(require("./BaseInterceptor")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var InvokeFetch = /*#__PURE__*/function (_BaseInterceptor) { _inherits(InvokeFetch, _BaseInterceptor); var _super = _createSuper(InvokeFetch); function InvokeFetch(fetch) { var _this; _classCallCheck(this, InvokeFetch); _this = _super.call(this); // Set the fetch function to execute in the context of window instead of // instance of OutboundFetch (e.g. the "this" in fetch is set to window instead // of instance of OutboundFetch). This is required to prevent browser from // complaining illegal invocation of fetch. _this._fetch = fetch.bind(window); return _this; } _createClass(InvokeFetch, [{ key: "invoke", value: function () { var _invoke = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(resource, init) { return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return this._fetch(resource, init); case 2: return _context.abrupt("return", _context.sent); case 3: case "end": return _context.stop(); } } }, _callee, this); })); function invoke(_x, _x2) { return _invoke.apply(this, arguments); } return invoke; }() }]); return InvokeFetch; }(_BaseInterceptor2["default"]); function initialize() { if ('fetch' in window) { /* The following function is designed in such a way so that it can chain a list of 'with' interceptors and finally invoke as a function. Example: fetch .with(new A()) .with(new B())("http://file-api.appzmonster.com", { method: 'GET', mode: 'cors' }); */ var FetchManager = function FetchManager(interceptor) { var _this2 = this; if (_typeof(interceptor) !== 'object') { throw new Error('Interceptor must be an instance of BaseInterceptor class'); } this._interceptors = [].concat(interceptor); var fetchRequest = /*#__PURE__*/function () { var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(resource, init) { var i, _interceptor, interceptors; return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (!(_this2._interceptors.length > 0)) { _context2.next = 14; break; } /* Sample of interceptors: A, B, C Iteration (index = 2): interceptor = C Iteration (index = 1): interceptor = C, B.setNextInterceptor(C), interceptor = B Iteration (index = 0): interceptor = B, A.setNextInterceptor(B), interceptor = A */ i = 0; _interceptor = null; interceptors = _this2._interceptors.concat(new InvokeFetch(fetch)); for (i = interceptors.length - 1; i >= 0; i--) { if (_interceptor != null) { interceptors[i]._setNextInterceptor(_interceptor); } _interceptor = interceptors[i]; } if (!(_interceptor != null)) { _context2.next = 11; break; } _context2.next = 8; return _interceptor.invoke(resource, init); case 8: return _context2.abrupt("return", _context2.sent); case 11: return _context2.abrupt("return", null); case 12: _context2.next = 17; break; case 14: _context2.next = 16; return fetch(resource, init); case 16: return _context2.abrupt("return", _context2.sent); case 17: case "end": return _context2.stop(); } } }, _callee2); })); return function fetchRequest(_x3, _x4) { return _ref.apply(this, arguments); }; }(); fetchRequest["with"] = function (interceptor) { if (_typeof(interceptor) !== 'object') { throw new Error('Interceptor must be an instance of BaseInterceptor class'); } _this2._interceptors.push(interceptor); return fetchRequest; }; return fetchRequest; }; if ('with' in window.fetch === true) { if (typeof window.fetch["with"] !== 'function') { console.error('Unable to enable fetch-interceptor feature to fetch api because \'with\' property is already in use'); return; } return; } var fetch = window.fetch; fetch["with"] = function (interceptor) { return new FetchManager(interceptor); }; } else { console.error('Unable to enable fetch-interceptor feature because browser does not support fetch api'); } } var _default = initialize; exports["default"] = _default;