/
sw.js
62 lines (52 loc) · 1.38 KB
/
sw.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
/* globals clients */
/* eslint-disable no-restricted-globals */
const fileCache = Object.create(null)
function getCache (name) {
if (!fileCache[name]) {
fileCache[name] = Object.create(null)
}
return fileCache[name]
}
self.addEventListener('install', (event) => {
console.log('Installing Uppy Service Worker...')
event.waitUntil(Promise.resolve()
.then(() => self.skipWaiting()))
})
self.addEventListener('activate', (event) => {
event.waitUntil(self.clients.claim())
})
function sendMessageToAllClients (msg) {
clients.matchAll().then((clients) => {
clients.forEach((client) => {
client.postMessage(msg)
})
})
}
function addFile (store, file) {
getCache(store)[file.id] = file.data
console.log('Added file blob to service worker cache:', file.data)
}
function removeFile (store, fileID) {
delete getCache(store)[fileID]
console.log('Removed file blob from service worker cache:', fileID)
}
function getFiles (store) {
sendMessageToAllClients({
type: 'uppy/ALL_FILES',
store,
files: getCache(store),
})
}
self.addEventListener('message', (event) => {
switch (event.data.type) {
case 'uppy/ADD_FILE':
addFile(event.data.store, event.data.file)
break
case 'uppy/REMOVE_FILE':
removeFile(event.data.store, event.data.fileID)
break
case 'uppy/GET_FILES':
getFiles(event.data.store)
break
}
})