diff options
Diffstat (limited to 'src/mixins/subUtils.pug')
-rw-r--r-- | src/mixins/subUtils.pug | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/src/mixins/subUtils.pug b/src/mixins/subUtils.pug new file mode 100644 index 0000000..7f40bf4 --- /dev/null +++ b/src/mixins/subUtils.pug | |||
@@ -0,0 +1,49 @@ | |||
1 | - | ||
2 | script(defer). | ||
3 | async function toggleSub(sub) { | ||
4 | let thinger = document.getElementById(`thinger_${sub}`); | ||
5 | if (thinger.innerText === 'unsubscribe') { | ||
6 | await doThing(sub, 'unsubscribe'); | ||
7 | } else { | ||
8 | await doThing(sub, 'subscribe'); | ||
9 | } | ||
10 | } | ||
11 | |||
12 | function getCookie(name) { | ||
13 | const value = `; ${document.cookie}`; | ||
14 | const parts = value.split(`; ${name}=`); | ||
15 | if (parts.length === 2) return parts.pop().split(";").shift(); | ||
16 | } | ||
17 | |||
18 | async function doThing(sub, thing) { | ||
19 | const jwtToken = getCookie("auth_token"); | ||
20 | const response = await fetch(`/${thing}`, { | ||
21 | method: 'POST', | ||
22 | headers: { | ||
23 | 'Authorization': `Bearer ${jwtToken}`, | ||
24 | 'Content-Type': 'application/json', | ||
25 | }, | ||
26 | body: JSON.stringify({ subreddit: sub }), | ||
27 | }); | ||
28 | |||
29 | let thinger = document.getElementById(`thinger_${sub}`); | ||
30 | if (thing === 'subscribe') { | ||
31 | thinger.innerText = 'unsubscribe'; | ||
32 | } else { | ||
33 | thinger.innerText = 'subscribe'; | ||
34 | } | ||
35 | |||
36 | if (!response.ok) { | ||
37 | console.error(response); | ||
38 | console.error(`Failed to do ${thing}`); | ||
39 | } | ||
40 | } | ||
41 | |||
42 | function toggleDetails(details_id) { | ||
43 | var detailsElement = document.getElementById(details_id); | ||
44 | if (detailsElement) { | ||
45 | detailsElement.open = !detailsElement.open; | ||
46 | } | ||
47 | } | ||
48 | |||
49 | |||