change to normal function and use async/await

This commit is contained in:
Thomas Rupprecht 2021-09-22 22:49:30 +02:00
parent 7aaf0d9840
commit 05d2d257e2
2 changed files with 60 additions and 51 deletions

View File

@ -1,20 +1,20 @@
const fetchJson = (url) => { function fetchJson(url) {
return fetch(url).then((response) => (response.json())); return fetch(url).then((response) => (response.json()));
}; }
const fetchCalendar = (days = 28) => { function fetchCalendar(days = 28) {
let url = `${Config.calenderUrl}?o=json`; let url = `${Config.calenderUrl}?o=json`;
if (days) { if (days) {
url += `&r=${days}`; url += `&r=${days}`;
} }
return fetchJson(url); return fetchJson(url);
}; }
const fetchSpaceApi = () => { function fetchSpaceApi() {
return fetchJson(Config.spaceApiUrl); return fetchJson(Config.spaceApiUrl);
}; }
const updateBadge = (open) => { async function updateBadge(open) {
let badgeText, badgeColor; let badgeText, badgeColor;
if (open) { if (open) {
badgeText = browser.browserAction.setBadgeText({text: 'open'}); badgeText = browser.browserAction.setBadgeText({text: 'open'});
@ -23,56 +23,58 @@ const updateBadge = (open) => {
badgeText = browser.browserAction.setBadgeText({text: ''}); badgeText = browser.browserAction.setBadgeText({text: ''});
badgeColor = browser.browserAction.setBadgeBackgroundColor({color: null}); badgeColor = browser.browserAction.setBadgeBackgroundColor({color: null});
} }
Promise.all([badgeText, badgeColor]) try {
.then() await Promise.all([badgeText, badgeColor]);
.catch((error) => { } catch (error) {
console.error(error); console.error(error);
}); }
}; }
const sendNotification = (open) => { function sendNotification(open) {
browser.notifications.create('notification-id', { browser.notifications.create('notification-id', {
type: 'basic', type: 'basic',
iconUrl: browser.runtime.getURL('icons/logo.svg'), iconUrl: browser.runtime.getURL('icons/logo.svg'),
title: 'Space Status', title: 'Space Status',
message: `Space ist jetzt ${open ? 'offen' : 'geschlossen'}.` message: `Space ist jetzt ${open ? 'offen' : 'geschlossen'}.`
}); });
}; }
const fetchNewData = () => { async function fetchNewData() {
fetchCalendar().then((json) => { try {
const json = await fetchCalendar();
window.calendar = json; window.calendar = json;
}).catch((error) => { } catch (error) {
console.error(error); console.error(error);
}); }
fetchSpaceApi().then((json) => { try {
const json = await fetchSpaceApi();
if (window.spaceApi && window.spaceApi.state.open !== json.state.open) { if (window.spaceApi && window.spaceApi.state.open !== json.state.open) {
sendNotification(json.state.open) sendNotification(json.state.open)
} }
window.spaceApi = json; window.spaceApi = json;
updateBadge(window.spaceApi.state.open); updateBadge(window.spaceApi.state.open);
}).catch((error) => { } catch (error) {
console.error(error); console.error(error);
}); }
}; }
let intervalHandler = null; let intervalHandler = null;
const stopFetching = () => { function stopFetching() {
if (intervalHandler !== null) { if (intervalHandler !== null) {
clearInterval(intervalHandler); clearInterval(intervalHandler);
intervalHandler = null; intervalHandler = null;
} }
}; }
const startFetching = () => { function startFetching() {
fetchNewData(); fetchNewData();
if (intervalHandler === null) { if (intervalHandler === null) {
intervalHandler = setInterval(() => { intervalHandler = setInterval(() => {
fetchNewData(); fetchNewData();
}, Config.refreshTimeout); }, Config.refreshTimeout);
} }
}; }
window.addEventListener('offline', () => { window.addEventListener('offline', () => {
stopFetching(); stopFetching();

View File

@ -1,25 +1,32 @@
Array.from(document.getElementsByClassName('link')).forEach((element) => { async function linkElementClickListener(event) {
element.addEventListener('click', (event) => { try {
const newTab = browser.tabs.create({ const tab = await browser.tabs.create({url: event.currentTarget.dataset.url});
url: event.currentTarget.dataset.url // console.log(tab);
}); } catch (error) {
newTab.then((data) => { console.error(error);
// console.log(data); }
}).catch((error) => { }
console.error(error);
}); async function init() {
const linkElements = Array.from(document.getElementsByClassName('link'));
linkElements.forEach((linkElement) => {
linkElement.addEventListener('click', linkElementClickListener);
}); });
});
browser.runtime.getBackgroundPage().then((page) => { try {
updateNextEvent(page.calendar); const page = await browser.runtime.getBackgroundPage();
updateSpaceApiJson(page.spaceApi); console.log(page);
updateState(page.spaceApi);
}).catch((error) => {
console.error(error);
});
const updateNextEvent = (nextEvents) => { updateNextEvent(page.calendar);
updateSpaceApiJson(page.spaceApi);
updateState(page.spaceApi);
} catch (error) {
console.error(error);
}
}
init();
function updateNextEvent(nextEvents) {
const calendarElement = document.getElementById('calendar'); const calendarElement = document.getElementById('calendar');
calendarElement.innerText = ''; calendarElement.innerText = '';
@ -54,18 +61,18 @@ const updateNextEvent = (nextEvents) => {
} }
calendarElement.append(divElement); calendarElement.append(divElement);
}); });
}; }
const updateSpaceApiJson = (spaceApi) => { function updateSpaceApiJson(spaceApi) {
const spaceApiElement = document.querySelector('#space-api code'); const spaceApiElement = document.querySelector('#space-api code');
const json = JSON.stringify(spaceApi, null, 2).replace(/ /g, '&nbsp;').replace(/\n/g, '<br/>'); const json = JSON.stringify(spaceApi, null, 2).replace(/ /g, '&nbsp;').replace(/\n/g, '<br/>');
spaceApiElement.innerHTML = json; spaceApiElement.innerHTML = json;
// const jsonNode = document.createTextNode(json); // const jsonNode = document.createTextNode(json);
// spaceApiElement.innerText = ''; // spaceApiElement.innerText = '';
// spaceApiElement.append(jsonNode); // spaceApiElement.append(jsonNode);
}; }
const updateState = (spaceApi) => { function updateState(spaceApi) {
const stateElement = document.getElementById('state'); const stateElement = document.getElementById('state');
const since = new Date(spaceApi.state.lastchange * 1000); const since = new Date(spaceApi.state.lastchange * 1000);
const sinceStr = ` seit <time datetime="${since.toISOString()}">${since.toLocaleString([], {dateStyle: "short", timeStyle: "short"})}</time>`; const sinceStr = ` seit <time datetime="${since.toISOString()}">${since.toLocaleString([], {dateStyle: "short", timeStyle: "short"})}</time>`;
@ -74,4 +81,4 @@ const updateState = (spaceApi) => {
} else { } else {
stateElement.innerHTML = `<img src="../icons/font-awesome/lock-solid.svg" width="19" height="19" alt="Geschlossen" />Geschlossen ${sinceStr}`; stateElement.innerHTML = `<img src="../icons/font-awesome/lock-solid.svg" width="19" height="19" alt="Geschlossen" />Geschlossen ${sinceStr}`;
} }
}; }