"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = throttleAdapterEnhancer;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _cache = _interopRequireDefault(require("../cache"));

var _utils = require("./utils");

function throttleAdapterEnhancer(adapter) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var _options$threshold = options.threshold,
      threshold = _options$threshold === void 0 ? 1000 : _options$threshold,
      _options$cache = options.cache,
      cache = _options$cache === void 0 ? new _cache["default"]({
    max: 10
  }) : _options$cache;

  var recordCacheWithRequest = function recordCacheWithRequest(index, config) {
    var responsePromise = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
      var response;
      return _regenerator["default"].wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              _context.next = 3;
              return adapter(config);

            case 3:
              response = _context.sent;
              cache.set(index, {
                timestamp: Date.now(),
                value: Promise.resolve(response)
              });
              return _context.abrupt("return", response);

            case 8:
              _context.prev = 8;
              _context.t0 = _context["catch"](0);
              cache.del(index);
              throw _context.t0;

            case 12:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[0, 8]]);
    }))();
    cache.set(index, {
      timestamp: Date.now(),
      value: responsePromise
    });
    return responsePromise;
  };

  return function (config) {
    var index = (0, _utils.buildURLWithAxiosConfig)(config);
    var now = Date.now();
    var cachedRecord = cache.get(index) || {
      timestamp: now
    };

    if (now - cachedRecord.timestamp <= threshold) {
      var responsePromise = cachedRecord.value;

      if (responsePromise) {
        if (process.env.LOGGER_LEVEL === 'info') {
          // eslint-disable-next-line no-console
          console.info("request cached by throttle adapter: ".concat(index));
        }

        return responsePromise;
      }
    }

    return recordCacheWithRequest(index, config);
  };
}
//# sourceMappingURL=throttleAdapterEnhancer.js.map
