summaryrefslogtreecommitdiff
path: root/src/aggietime.js
blob: 793481c1287ed6fa5fe258397de86865efc81570 (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
import {
  AGGIETIME_URI,
  AGGIETIME_DOMAIN,
  USER_PATH,
  USER_CACHE_EXP_SEC,
  CLOCKIN_PATH,
} from "./constants.js";

import { client } from "./axios_client.js";

import expireCache from "expire-cache";

const replace_path_args = (path, map) =>
  path.replaceAll(/:([a-zA-Z0-9_]+)/g, (_, key) => map[key]);

const get_user_position_or_specified = async (position) => {
  const { positions } = await get_user_info();

  if (!position && positions.length != 1) {
    throw "Must specify a position when there's not only one to choose from";
  } else if (!position) {
    position = positions[0];
  }

  return position;
};

export const get_user_info = async () => {
  if (!expireCache.get("user")) {
    const user = await client
      .get(`${AGGIETIME_URI}/${USER_PATH}`)
      .then(({ data, config }) => {
        const csrf_token = config.jar
          .toJSON()
          .cookies.find(
            ({ domain, key }) =>
              domain === AGGIETIME_DOMAIN && key === "XSRF-TOKEN"
          ).value;
        expireCache.set("aggietime-csrf", csrf_token);
        return data;
      });

    expireCache.set("user", user, USER_CACHE_EXP_SEC);
  }
  return expireCache.get("user");
};

export const clock_in = async ({ position } = {}) => {
  position = await get_user_position_or_specified(position);

  return await client.post(
    `${AGGIETIME_URI}/${replace_path_args(CLOCKIN_PATH, { position })}`,
    {
      comment: "",
    },
    {
      headers: {
        "X-XSRF-TOKEN": expireCache.get("aggietime-csrf"),
      },
    }
  );
};