aboutsummaryrefslogtreecommitdiff
path: root/src/mixins/subUtils.pug
blob: 7f40bf4c64b535b08bd6c6e37e0b287ecb175fbe (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
-
script(defer).
  async function toggleSub(sub) {
    let thinger = document.getElementById(`thinger_${sub}`);
    if (thinger.innerText === 'unsubscribe') {
      await doThing(sub, 'unsubscribe');
    } else {
      await doThing(sub, 'subscribe');
    }
  }

  function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(";").shift();
  }

  async function doThing(sub, thing) {
    const jwtToken = getCookie("auth_token");
    const response = await fetch(`/${thing}`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${jwtToken}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ subreddit: sub }),
    });

    let thinger = document.getElementById(`thinger_${sub}`);
    if (thing === 'subscribe') {
      thinger.innerText = 'unsubscribe';
    } else {
      thinger.innerText = 'subscribe';
    }

    if (!response.ok) {
      console.error(response);
      console.error(`Failed to do ${thing}`);
    }
  }

  function toggleDetails(details_id) {
    var detailsElement = document.getElementById(details_id);
    if (detailsElement) {
      detailsElement.open = !detailsElement.open;
    }
  }