<commit_before>// This is the JS API to talk to api.participedia.xyz
import queryString from "query-string";
import authService from "./AuthService";
import store from "store";
import Raven from "raven-js";

let APIURL = process.env.REACT_APP_API_URL; // eslint-disable-line no-undef

if (!APIURL) {
  console.error(
    "No API URL was found. REACT_APP_API_URL should be set in environment variables."
  );
}

const signedFetch = function(url, method, payload) {
  let opts = {
    method: method || "get",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json"
    }
  };
  let profile = store.get("profile");
  if (profile) {
    profile = JSON.parse(profile);
    if (authService.isAuthenticated()) {
      opts["headers"]["Authorization"] = "Bearer " + authService.getToken();
      opts["headers"]["X-Auth0-Name"] = profile.name;
      opts["headers"]["X-Auth0-UserId"] = profile.user_id;
    }
    // console.log("doing signed call to", url);
  } else {
    // console.log("doing unsigned call to", url);
    delete opts["headers"]["authorization"];
  }
  if (payload) opts.body = JSON.stringify(payload);
  return fetch(url, opts);
};

class API {
  secureFetch = signedFetch;

  fetchGeoJSON = function(countryCode) {
    let url = APIURL + "/countries/" + countryCode + ".geo.json";
    return fetch(url).then(response => response.json()).catch(function(error) {
      console.error(
        `There has been a problem with your fetch operation: (${url}) ${error}`
      );
      return error;
    });
  };

  countsByCountry = function() {
    let url = APIURL + "/case/countsByCountry";
    return fetch(url)
      .then(response => response.json())
      .then(function(json) {
        return json.data.countryCounts;
      })
      .catch(function(error) {
        console.error(
          `There has been a problem with your fetch operation: (${url}) ${error}`
        );
        return error;
      });
  };

  performSearch = function(queryArgs) {
    let querystring = queryString.stringify(queryArgs);
    let url = `${APIURL}/search?${querystring}`;
    // console.log("queryArgs", queryArgs);
    // console.log("DOING SEARCH", url);
    return fetch(url).then(response => response.json()).catch(function(error) {
      console.log(
        `There has been a problem with your fetch operation: (${url}) ${error}`
      );
      return error;
    });
  };

  searchMapTokens = function(search) {
    let url;
    if (search) {
      url = APIURL + `/search${search}&resultType=map`;
    } else {
      url = APIURL + `/search?resultType=map`;
    }
    return signedFetch(url, "get")
      .then(response => response.json())
      .then(json => json.results)
      .catch(function(error) {
        console.error(
          `There has been a problem with your fetch operation: (${url}) ${error}`
        );
        throw error;
      });
  };

  fetchCaseById = function(caseId) {
    let url = APIURL + "/case/" + caseId;
    return signedFetch(url, "get")
      .then(response => response.json())
      .then(json => json.data)
      .catch(function(error) {
        console.error(
          `There has been a problem with your fetch operation: (${url}) ${error}`
        );
        throw error;
      });
  };

  saveNewThing = function(thingType, obj) {
    // console.log("saveNewThing", thingType, obj);
    if (
      thingType !== "case" &&
      thingType !== "method" &&
      thingType !== "organization"
    ) {
      let error = `Can only create cases, methods, and organizations. You sent: ${thingType}`;
      console.error(error);
      throw error;
    }
    let url = APIURL + "/" + thingType + "/new";
    // console.log("sending object", obj);
    return signedFetch(url, "POST", obj)
      .then(response => response.json())
      .then(function(response) {
        if (!response.OK) {
          console.log("Error doing saveNewThing's signedFetch: ", response);
          throw response.error;
        }
        // console.log("got response", response);
        return response.data;
      })
      .then(function(json) {
        // console.log("GOT JSON", json);
        obj.id = json.thingid;
        return obj;
      })
      .catch(function(error) {
        if (error) {
          let errorMsg = `There has been a problem with saving the ${thingType}: (${url}) ${JSON.stringify(
            error
          )}`;

          Raven.captureMessage(errorMsg, {
            level: "error"
          });
          console.error(errorMsg);
          // throw error; XXX OIDP
        }
      });<commit_msg>log the thing that failed to save.<commit_after>// This is the JS API to talk to api.participedia.xyz
import queryString from "query-string";
import authService from "./AuthService";
import store from "store";
import Raven from "raven-js";

let APIURL = process.env.REACT_APP_API_URL; // eslint-disable-line no-undef

if (!APIURL) {
  console.error(
    "No API URL was found. REACT_APP_API_URL should be set in environment variables."
  );
}

const signedFetch = function(url, method, payload) {
  let opts = {
    method: method || "get",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json"
    }
  };
  let profile = store.get("profile");
  if (profile) {
    profile = JSON.parse(profile);
    if (authService.isAuthenticated()) {
      opts["headers"]["Authorization"] = "Bearer " + authService.getToken();
      opts["headers"]["X-Auth0-Name"] = profile.name;
      opts["headers"]["X-Auth0-UserId"] = profile.user_id;
    }
    // console.log("doing signed call to", url);
  } else {
    // console.log("doing unsigned call to", url);
    delete opts["headers"]["authorization"];
  }
  if (payload) opts.body = JSON.stringify(payload);
  return fetch(url, opts);
};

class API {
  secureFetch = signedFetch;

  fetchGeoJSON = function(countryCode) {
    let url = APIURL + "/countries/" + countryCode + ".geo.json";
    return fetch(url).then(response => response.json()).catch(function(error) {
      console.error(
        `There has been a problem with your fetch operation: (${url}) ${error}`
      );
      return error;
    });
  };

  countsByCountry = function() {
    let url = APIURL + "/case/countsByCountry";
    return fetch(url)
      .then(response => response.json())
      .then(function(json) {
        return json.data.countryCounts;
      })
      .catch(function(error) {
        console.error(
          `There has been a problem with your fetch operation: (${url}) ${error}`
        );
        return error;
      });
  };

  performSearch = function(queryArgs) {
    let querystring = queryString.stringify(queryArgs);
    let url = `${APIURL}/search?${querystring}`;
    // console.log("queryArgs", queryArgs);
    // console.log("DOING SEARCH", url);
    return fetch(url).then(response => response.json()).catch(function(error) {
      console.log(
        `There has been a problem with your fetch operation: (${url}) ${error}`
      );
      return error;
    });
  };

  searchMapTokens = function(search) {
    let url;
    if (search) {
      url = APIURL + `/search${search}&resultType=map`;
    } else {
      url = APIURL + `/search?resultType=map`;
    }
    return signedFetch(url, "get")
      .then(response => response.json())
      .then(json => json.results)
      .catch(function(error) {
        console.error(
          `There has been a problem with your fetch operation: (${url}) ${error}`
        );
        throw error;
      });
  };

  fetchCaseById = function(caseId) {
    let url = APIURL + "/case/" + caseId;
    return signedFetch(url, "get")
      .then(response => response.json())
      .then(json => json.data)
      .catch(function(error) {
        console.error(
          `There has been a problem with your fetch operation: (${url}) ${error}`
        );
        throw error;
      });
  };

  saveNewThing = function(thingType, obj) {
    // console.log("saveNewThing", thingType, obj);
    if (
      thingType !== "case" &&
      thingType !== "method" &&
      thingType !== "organization"
    ) {
      let error = `Can only create cases, methods, and organizations. You sent: ${thingType}`;
      console.error(error);
      throw error;
    }
    let url = APIURL + "/" + thingType + "/new";
    // console.log("sending object", obj);
    return signedFetch(url, "POST", obj)
      .then(response => response.json())
      .then(function(response) {
        if (!response.OK) {
          console.log("Error doing saveNewThing's signedFetch: ", response);
          throw response.error;
        }
        // console.log("got response", response);
        return response.data;
      })
      .then(function(json) {
        // console.log("GOT JSON", json);
        obj.id = json.thingid;
        return obj;
      })
      .catch(function(error) {
        if (error) {
          let errorMsg = `There has been a problem with saving the ${thingType}: (${url}) ${JSON.stringify(
            error
          )}`;

          Raven.captureMessage(
            "error doing signedfetch " +
              JSON.stringify(obj) +
              " -> " +
              errorMsg,
            {
              level: "error"
            }
          );
          console.error(errorMsg);
          // throw error; XXX OIDP
        }
      });
{'fraction_non_alphanumeric': 0.15076724970490396, 'fraction_numerical': 0.00042923060414207535, 'mean_word_length': 2.4101719721917307, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 20, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1408133', 'n_tokens_mistral': 2786, 'n_tokens_neox': 2791, 'n_words': 687}