This repository was archived by the owner on Nov 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynamic-cache.js
55 lines (47 loc) · 1.52 KB
/
dynamic-cache.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
export default class DynamicCache {
static async cleanup () {
const cacheKeys = await window.caches.keys()
await Promise.all(cacheKeys
// .filter(key => key.startsWith('dynamic-cache:')) //TODO: enable this in prod
.map(key => window.caches.delete(key))
)
}
static install () {
return new Promise(async resolve => {
await DynamicCache.cleanup()
const reg = await navigator
.serviceWorker
.register('/dynamic-cache-service-worker.js', { scope: '/' })
if (reg.active) return resolve(reg.active)
reg.onupdatefound = () => {
reg.installing.onstatechange = event => {
if (event.target.state === 'activated') {
resolve(event.target)
}
}
}
reg.update()
})
}
constructor (namespace = 'test', headers = { 'Content-Type': 'application/javascript' }) {
this.namespace = namespace
this.headers = headers
this.path = '/dynamic-cache/cache/' + this.namespace
}
toJSON () {
return {
namespace: this.namespace,
headers: this.headers,
path: this.path
}
}
async put (filename, content, headers = this.headers) {
filename = `${this.path}/${filename}`
const req = new Request(filename, { method: 'GET', headers })
const res = new Response(content, { status: 200, headers })
const cache = await caches.open('dynamic-cache:' + this.namespace)
await cache.put(req, res)
this.onchange?.(location.origin + filename)
return location.origin + filename
}
}