{"size": 1390, "ext": "js", "max_stars_repo_path": "src/js/providers/api.js", "max_stars_repo_name": "brainy099/demoit", "max_stars_repo_stars_event_min_datetime": "2018-11-03T17:20:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T10:12:15.000Z", "max_issues_repo_path": "src/js/providers/api.js", "max_issues_repo_name": "brainy099/demoit", "max_issues_repo_issues_event_min_datetime": "2018-12-01T06:19:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-22T09:02:27.000Z", "max_forks_repo_path": "src/js/providers/api.js", "max_forks_repo_name": "brainy099/demoit", "max_forks_repo_forks_event_min_datetime": "2018-11-05T12:10:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T08:35:30.000Z"}
{"max_stars_count": 151, "max_issues_count": 10, "max_forks_count": 43, "avg_line_length": 20.7462686567, "max_line_length": 83, "alphanum_fraction": 0.6014388489}
/* eslint-disable consistent-return, no-use-before-define */
import { SAVE_DEMO_URL, GET_DEMOS_URL } from '../constants';

let requestInFlight = false;
let queue = [];

const emptyQueue = function () {
  if (queue.length > 0) {
    const { state, token, diff } = queue.shift();

    saveDemo(state, token, diff);
  }
};

const saveDemo = async function (state, token, diff) {
  if (requestInFlight) {
    queue.push({ state, token, diff });
    return;
  }

  try {
    requestInFlight = true;
    const response = await fetch(SAVE_DEMO_URL, {
      method: 'POST',
      body: JSON.stringify({ state, a: diff }),
      headers: { token }
    });

    const result = await response.json();

    requestInFlight = false;
    emptyQueue();

    if (result.error) {
      console.error(result.error);
    } else if (result.demoId) {
      return result.demoId;
    }
    console.log(result);
  } catch (error) {
    emptyQueue();
    console.error(error);
  }
};

const getDemos = async function (id, token) {
  try {
    const response = await fetch(GET_DEMOS_URL + '/' + id, { headers: { token } });
    const result = await response.json();

    if (result.error) {
      console.error(result.error);
    } else if (result) {
      return result;
    } else {
      console.log(result);
    }
  } catch (error) {
    console.error(error);
  }
};

export default {
  saveDemo,
  getDemos
};
