sensorui/public/serviceworker.js

53 lines
1.3 KiB
JavaScript

// This code executes in its own worker or thread
self.addEventListener("install", event => {
checkNotificationPromise();
interval = setInterval(() => fetchAndCacheLatestNews(), 1000);
});
self.addEventListener("fetch", (e) => {
console.log(`[Service Worker] Fetched resource ${e.request.url}`);
});
let interval = 0;
function handleNotification(title, notif) {
if (checkNotificationPromise()) {
self.registration.showNotification(title, notif);
} else {
self.registration.showNotification(title, notif);
}
}
async function fetchAndCacheLatestNews() {
const response = await fetch('/api/teasense');
const data = await response.json();
const temp = data[data.length - 1].value;
if (temp) {
if (temp >= ALERT_THRESHOLD) {
handleNotification('TeaSense Alert', {
body: '♨️ ',
tag: 1,
});
} else if (temp < ALERT_THRESHOLD && temp > WARNING_THRESHOLD) {
handleNotification('TeaSense Warning', {
body: '🫖',
tag: 1,
});
}
}
}
function checkNotificationPromise() {
try {
Notification.requestPermission().then();
} catch (e) {
return false;
}
return true;
}
const ALERT_THRESHOLD = 80.0;
const WARNING_THRESHOLD = 75.0;