{"size": 1469, "ext": "js", "max_stars_repo_path": "lib/RequestManager.js", "max_stars_repo_name": "thaerlabs/axios-cancel", "max_stars_repo_stars_event_min_datetime": "2017-01-16T09:39:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T07:58:50.000Z", "max_issues_repo_path": "lib/RequestManager.js", "max_issues_repo_name": "thaerlabs/axios-cancel", "max_issues_repo_issues_event_min_datetime": "2017-01-16T10:05:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-30T17:03:22.000Z", "max_forks_repo_path": "lib/RequestManager.js", "max_forks_repo_name": "thaerlabs/axios-cancel", "max_forks_repo_forks_event_min_datetime": "2017-10-19T17:16:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T15:39:00.000Z"}
{"max_stars_count": 50, "max_issues_count": 10, "max_forks_count": 13, "avg_line_length": 26.2321428571, "max_line_length": 110, "alphanum_fraction": 0.6494213751}
export default class RequestManager {

  constructor(options = {}) {
    this.options = options;
    this.pendingRequests = {};
  }

  addRequest(requestId, cancelFn) {

    this.log(`adding request \`${requestId}\``);

    if (this.has(requestId)) {
      this.cancelRequest(requestId, `\`cancelRequest(${requestId})\` from \`RequestManager.addRequest\`.
      Found duplicate pending request.`);
      this.pendingRequests[requestId] = cancelFn;
    } else {
      this.pendingRequests[requestId] = cancelFn;
    }
  }

  removeRequest(requestId) {
    this.log(`removing request \`${requestId}\``);

    delete this.pendingRequests[requestId];
  }

  cancelRequest(requestId, reason = `\`cancelRequest(${requestId})\` from \`RequestManager.cancelRequest\``) {
    this.log(`cancelling request \`${requestId}\``);

    if (this.has(requestId)
    && typeof this.pendingRequests[requestId] === 'function') {
      this.pendingRequests[requestId](reason);
      this.removeRequest(requestId);

      this.log(`request \`${requestId}\` cancelled`);
    }
  }

  cancelAllRequests(reason) {
    for (let requestId in this.pendingRequests) {
      let _reason = reason || `\`cancelRequest(${requestId})\` from \`RequestManager.cancelAllRequests\``;
      this.cancelRequest(requestId, _reason);
    }
  }

  has(requestId) {
    return !!this.pendingRequests[requestId];
  }

  log(message) {
    if (this.options.debug === true) {
      console.log(message);
    }
  }
}
