优化服务工作者

This commit is contained in:
jxxghp
2025-07-07 22:56:36 +08:00
parent 27c7a842db
commit 9fc5291fec
+34 -18
View File
@@ -157,12 +157,12 @@ async function deleteOldCaches() {
const cacheNames = await caches.keys() const cacheNames = await caches.keys()
await Promise.all( await Promise.all(
cacheNames.map(async (cacheName) => { cacheNames.map(async cacheName => {
if (!cacheWhitelist.includes(cacheName)) { if (!cacheWhitelist.includes(cacheName)) {
console.log('Deleting old cache:', cacheName) console.log('Deleting old cache:', cacheName)
return caches.delete(cacheName) return caches.delete(cacheName)
} }
}) }),
) )
} }
@@ -212,7 +212,7 @@ async function monitorCacheSize() {
cacheSizes, cacheSizes,
totalSize, totalSize,
totalSizeMB: (totalSize / 1024 / 1024).toFixed(2), totalSizeMB: (totalSize / 1024 / 1024).toFixed(2),
} },
}) })
}) })
@@ -344,12 +344,12 @@ self.addEventListener('fetch', event => {
JSON.stringify({ JSON.stringify({
success: true, success: true,
queued: true, queued: true,
message: '请求已加入离线队列,将在网络恢复后自动同步' message: '请求已加入离线队列,将在网络恢复后自动同步',
}), }),
{ {
status: 202, status: 202,
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
} },
) )
} }
})(), })(),
@@ -405,16 +405,19 @@ async function addToSyncQueue(request: Request) {
async function processSyncQueue() { async function processSyncQueue() {
const db = await openDB() const db = await openDB()
// 使用专用的 "sync" store,并开启 readwrite 事务(便于后续删除) // 先用只读事务获取所有同步项
const tx = db.transaction(['sync'], 'readwrite')
const store = tx.objectStore('sync')
const items: Array<any> = await new Promise((resolve, reject) => { const items: Array<any> = await new Promise((resolve, reject) => {
const tx = db.transaction(['sync'], 'readonly')
const store = tx.objectStore('sync')
const req = store.getAll() const req = store.getAll()
req.onsuccess = () => resolve(req.result) req.onsuccess = () => resolve(req.result)
req.onerror = () => reject(req.error) req.onerror = () => reject(req.error)
}) })
// 收集需要删除的项目ID
const itemsToDelete: string[] = []
const itemsToDeleteExpired: string[] = []
for (const syncItem of items) { for (const syncItem of items) {
const key = syncItem.id const key = syncItem.id
try { try {
@@ -434,8 +437,8 @@ async function processSyncQueue() {
const response = await fetch(syncItem.url, init) const response = await fetch(syncItem.url, init)
if (response.ok) { if (response.ok) {
// 成功后删除同步项,并等待事务完成 // 成功后标记为需要删除
await del(key, 'sync') itemsToDelete.push(key)
// 通知客户端同步成功 // 通知客户端同步成功
const clients = await self.clients.matchAll() const clients = await self.clients.matchAll()
@@ -452,12 +455,29 @@ async function processSyncQueue() {
} catch (error) { } catch (error) {
console.error('Sync failed for item:', key, error) console.error('Sync failed for item:', key, error)
// 如果该同步项已存在超过 24 小时,则将其丢弃 // 如果该同步项已存在超过 24 小时,则标记为需要删除
if (Date.now() - syncItem.timestamp > 24 * 60 * 60 * 1000) { if (Date.now() - syncItem.timestamp > 24 * 60 * 60 * 1000) {
await del(key, 'sync') itemsToDeleteExpired.push(key)
} }
} }
} }
// 批量删除所有成功处理的项目和过期项目
const allItemsToDelete = [...itemsToDelete, ...itemsToDeleteExpired]
if (allItemsToDelete.length > 0) {
await new Promise<void>((resolve, reject) => {
const tx = db.transaction(['sync'], 'readwrite')
const store = tx.objectStore('sync')
// 批量删除所有标记的项目
allItemsToDelete.forEach(id => {
store.delete(id)
})
tx.oncomplete = () => resolve()
tx.onerror = () => reject(tx.error)
})
}
} }
// 初始化 Workbox // 初始化 Workbox
@@ -552,11 +572,7 @@ self.addEventListener('message', function (event) {
}) })
} else if (event.data && event.data.type === 'CLEANUP_CACHES') { } else if (event.data && event.data.type === 'CLEANUP_CACHES') {
// 手动触发缓存清理 // 手动触发缓存清理
Promise.all([ Promise.all([deleteOldCaches(), cleanupExpiredCaches(), monitorCacheSize()])
deleteOldCaches(),
cleanupExpiredCaches(),
monitorCacheSize()
])
.then(([, , cacheInfo]) => { .then(([, , cacheInfo]) => {
event.ports[0]?.postMessage({ success: true, cacheInfo }) event.ports[0]?.postMessage({ success: true, cacheInfo })
}) })