-
Notifications
You must be signed in to change notification settings - Fork 1
/
tile-worker.js
63 lines (55 loc) · 1.42 KB
/
tile-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
const cacheName = "tiles";
const cacheAssets = [];
const addResourcesToCache = async (resources) => {
const cache = await caches.open("v1");
await cache.addAll(resources);
};
self.addEventListener("install", (e) => {
e.waitUntil(addResourcesToCache(["/tile.index.json"]));
});
const zxyregex = new RegExp(/worker\-server\/(\d+\/\d+\/\d+)\.webp/);
async function makeTile(tilearray) {
const r = new Response(tilearray, {
status: 200,
headers: {
"Content-Type": "image/webp",
},
});
return r;
}
async function get(start, end) {
const response = await fetch("/chunk.tile", {
headers: {
Range: `bytes=${start}-${end}`,
},
});
const buf = await response.arrayBuffer();
return buf;
}
self.addEventListener("fetch", (ev) => {
const matches = zxyregex.exec(ev.request.url);
if (matches) {
ev.respondWith(
caches
.match("/tile.index.json")
.then((r) => {
return r.json();
})
.then((d) => {
if (matches[1] in d) {
// return new Response("hi")
const [start, end] = d[matches[1]];
return get(start, end).then((r) => {
return makeTile(r);
});
// ev.respondWith(res);
} else {
return fetch(ev.request);
}
})
);
} else {
console.log(`No matches found for ${ev.request}`);
ev.respondWith(fetch(ev.request.url));
}
});