pulse-whoop / service-worker.js
CSNET's picture
ช่วยแก้ code ต่อ และทำเว็บให้สมบรูณ์ที
f93e15c verified
Raw History Blame Contribute Delete
3.34 kB
const CACHE_NAME = 'chipat-health-v1.0.0';
const urlsToCache = [
'/',
'/index.html',
'/sleep.html',
'/activity.html',
'/nutrition.html',
'/profile.html',
'/style.css',
'/script.js',
'/components/navbar.js',
'/components/ai-coach-card.js',
'/components/hardware-status.js',
'/components/vital-circle.js',
'/components/mood-logger.js',
'/components/meal-logger-enhanced.js',
'https://cdn.tailwindcss.com',
'https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js',
'https://cdn.jsdelivr.net/npm/chart.js'
];
// Install event
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME)
.then((cache) => {
console.log('กำลังเปิด cache');
return cache.addAll(urlsToCache);
})
);
});
// Fetch event
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request)
.then((response) => {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request).then(
(response) => {
// Check if we received a valid response
if (!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
// Clone the response
const responseToCache = response.clone();
caches.open(CACHE_NAME)
.then((cache) => {
cache.put(event.request, responseToCache);
});
return response;
}
);
})
);
});
// Activate event
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (cacheName !== CACHE_NAME) {
return caches.delete(cacheName);
}
})
);
})
);
});
// Background sync for health data
self.addEventListener('sync', (event) => {
if (event.tag === 'health-data-sync') {
event.waitUntil(syncHealthData());
}
});
async function syncHealthData() {
try {
// Get pending data from IndexedDB
const pendingData = await getPendingHealthData();
for (const data of pendingData) {
// Send to server (in real app)
await fetch('/api/health-data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
// Remove from pending queue
await removePendingData(data.id);
}
console.log('ซิงค์ข้อมูลสุขภาพสำเร็จ');
} catch (error) {
console.error('ซิงค์ข้อมูลล้มเหลว:', error);
}
}