summaryrefslogtreecommitdiff
path: root/src/utils/shoelace.js
blob: 63b9c791ab45c104fd23d957029665bd49052f2d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
 * Storing footprints ... don't trip over your own shoelace!
 *
 * Usage:
 *   import { footprint } from 'utils/shoelace'
 *   footprint("egress")
 *   footpring("details", { id: 3 })
 */

const FINAL_DATE = "2021-12-01T00:00:00";
const SHOEBOX_CODE = "no6092";
const SHOELACE_CODE = "shoelace";

const API_HOST = atob("aHR0cHM6Ly9zaG9lYm94LmdpcmFmZmUubGlmZQ==");
const API_ENDPOINT = atob("L2FwaS92MS9zaG9l");

export const footprint = async (type, metadata = {}) => {
  if (new Date() > new Date(FINAL_DATE)) return;
  try {
    await post(API_ENDPOINT, {
      shoelace: getShoelace(),
      shoebox: SHOEBOX_CODE,
      type,
      metadata,
    });
  } catch (error) {
    // console.error(error);
    return;
  }
};

const getShoelace = () => {
  let shoelace = window.localStorage.getItem(SHOELACE_CODE);
  if (shoelace) {
    return shoelace;
  }
  shoelace = Math.random().toString(36).slice(2);
  window.localStorage.setItem(SHOELACE_CODE, shoelace);
  return shoelace;
};

/**
 * Perform a POST request to send data to an API.
 * @param  {String} href the URL to query
 * @param  {Object} data the data to submit
 * @return {Object}      the server response
 */
async function post(href, data) {
  return await requestWithMethod("POST", href, data);
}

/**
 * Perform an HTTP request.
 * @param  {String} method the HTTP method (GET, POST, PUT, DELETE)
 * @param  {String} href   the URL to query
 * @param  {Object} data   the data to submit (becomes a query string for GET, or FormData for all others)
 * @return {Object}        if successful, the API response. if JSON, deserialized.
 */
async function requestWithMethod(method, href, data) {
  const urlObject = new URL(API_HOST + href);
  const requestOptions = {
    method,
    headers: {},
    // headers: {
    //   Authorization: "Bearer " + getToken(),
    // },
    // mode: SHOEBOX_PRODUCTION ? "same-origin" : "cors",
    mode: "cors",
  };

  if (method === "GET") {
    if (data) {
      urlObject.search = new URLSearchParams(data).toString();
    }
  } else {
    requestOptions.headers["Content-Type"] = "application/json";
    requestOptions.body = JSON.stringify(data);
  }

  let response;
  response = await fetch(urlObject, requestOptions);
  if (response.ok) {
    switch (getContentTypeFromHeader(response)) {
      case "application/json":
        return await response.json();
    }
  }
  if (response.status === 403 || response.status === 404) {
    const errorData = await response.json();
    throw new Error(errorData.error);
  }
  throw new Error(response.status);
}