-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweekly-events.js
64 lines (58 loc) · 2.28 KB
/
weekly-events.js
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
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
async function getEvents() {
try {
let cacheDate;
if (localStorage.getItem('events-cache')) {
const { date, data: cacheData } = JSON.parse(localStorage.getItem('events-cache'));
cacheDate = date;
processData(cacheData, date);
}
const res = await fetch('https://lukio.raikas.dev/tiedotteet/events.json');
const data = await res.json();
const lastUpdated = new Date(res.headers.get('Date')).toLocaleString('fi');
if (cacheDate && lastUpdated === cacheDate) {
return;
}
processData(data, lastUpdated);
localStorage.setItem('events-cache', JSON.stringify({ date: lastUpdated, data }));
} catch (e) {
document.querySelector('#week-bulletin-events').innerHTML = 'Viikkotiedotteen haku epäonnistui :(';
console.error(e);
}
}
function processData(data, lastUpdated) {
const events = Object
.keys(data.events)
.map((date) => ({
date: capitalize(
new Date(date).toLocaleDateString(
'fi',
{ weekday: 'short', day: 'numeric', month: 'numeric', year: 'numeric'}
)
),
events: data.events[date].map((i) => i.replaceAll('\n', '<br>')).join("<br/>")
}))
.sort((a, b) => a.date - b.date)
.filter((i) => i.events !== "");
const upcoming = Object
.keys(data.upcoming)
.map((date) => ({
date: capitalize(
new Date(date).toLocaleDateString(
'fi',
{ weekday: 'short', day: 'numeric', month: 'numeric', year: 'numeric'}
)
),
events: data.upcoming[date].join("<br/>")
}))
.sort((a, b) => a.date - b.date)
.filter((i) => i.events !== "");
const weekEvents = events.map((event) => `<h4>${event.date}</h4><p>${event.events}</p>`).join("\n");
const extra = data.extra.length > 0 ? `<h4>Muuta ajankohtaista</h4><p>${data.extra.join("<br>")}</p>` : "";
const upcomingEvents = `<h4>Tulevaa</h4><p>${upcoming.map((event) => `<strong>${event.date}</strong>: ${event.events}`).join("<br>")}`;
document.querySelector('#week-bulletin-events').innerHTML = weekEvents + extra + upcomingEvents;
document.querySelector('#last-updated').innerHTML = lastUpdated;
}
getEvents();