-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.js
79 lines (73 loc) · 2.05 KB
/
worker.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import * as Comlink from 'comlink'
const refetchable = new Map()
const fetchId = (input, init) => {
const url = input.toString()
if (!init) {
return url
}
let id = url
for (const [key, value] of Object.entries(init).sort(([a], [b]) => a.localeCompare(b))) {
id = `${id}::${key}=${value.toString()}`
}
return id
}
setInterval(() => {
for (const [id, f] of refetchable) {
f.init = f.init || {}
const fetchedAt = f.fetchedAt || 0
const { refetch = 0, ..._init } = f.init
const now = Date.now()
if (now - refetch * 1000 > fetchedAt) {
f.fetchedAt = now
refetchable.set(id, f)
fetch(f.input, _init).then(async (res) => {
const headers = {}
for (const [key, value] of res.headers) {
headers[key] = value
}
const isJson = headers['content-type']?.startsWith('application/json')
const body = isJson ? await res.json() : await res.text()
return f.onFetch({
headers,
ok: res.ok,
redirected: res.redirected,
status: res.status,
statusText: res.statusText,
body,
})
})
}
}
}, 1000)
const background = {
cancel(input, init) {
const { refetch, ..._init } = init || {}
if (refetch) {
refetchable.delete(fetchId(input, _init))
}
},
fetch(input, onFetch, init) {
const { refetch, ..._init } = init || {}
if (refetch) {
refetchable.set(fetchId(input, _init), { input, init, onFetch, fetchedAt: 0 })
} else {
fetch(input, _init).then(async (res) => {
const headers = {}
for (const [key, value] of res.headers) {
headers[key] = value
}
const isJson = headers['content-type']?.startsWith('application/json')
const body = isJson ? await res.json() : await res.text()
return onFetch({
headers,
ok: res.ok,
redirected: res.redirected,
status: res.status,
statusText: res.statusText,
body,
})
})
}
},
}
Comlink.expose(background)