-
Notifications
You must be signed in to change notification settings - Fork 14
/
fetch-and-cache.ts
71 lines (58 loc) · 2.43 KB
/
fetch-and-cache.ts
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
export const CACHE = new Map();
export const CACHE_NAME = "EXTERNAL_FETCHES";
export const SUPPORTS_CACHE_API = "caches" in globalThis;
export const SUPPORTS_REQUEST_API = "Request" in globalThis;
export function requestKey(request: RequestInfo) {
return SUPPORTS_REQUEST_API && request instanceof Request ? request.url.toString() : request.toString()
}
export async function newRequest(request: RequestInfo, cache?: Cache, fetchOpts?: RequestInit, clone = true) {
const networkResponse: Response = await fetch(request, fetchOpts);
if (!fetchOpts?.method || (fetchOpts?.method && fetchOpts.method.toUpperCase() !== "GET"))
return networkResponse;
if (clone) {
const clonedResponse = networkResponse.clone();
if (SUPPORTS_CACHE_API && cache) {
cache.put(request, networkResponse);
} else {
const reqKey = requestKey(request);
CACHE.set(reqKey, networkResponse);
}
return clonedResponse;
}
if (SUPPORTS_CACHE_API && cache) {
cache.put(request, networkResponse);
} else {
const reqKey = requestKey(request);
CACHE.set(reqKey, networkResponse);
}
}
export let OPEN_CACHE: Cache;
export async function openCache() {
if (OPEN_CACHE) return OPEN_CACHE;
return (OPEN_CACHE = await caches.open(CACHE_NAME));
}
export async function getRequest(url: RequestInfo | URL, permanent = false, fetchOpts?: RequestInit) {
const request = SUPPORTS_REQUEST_API ? new Request(url.toString(), fetchOpts) : url.toString();
let response: Response;
let cache: Cache | undefined;
let cacheResponse: Response | undefined;
// In specific situations the browser will sometimes disable access to cache storage,
// so, I create my own in memory cache
if (SUPPORTS_CACHE_API) {
cache = await openCache();
cacheResponse = await cache.match(request);
} else {
const reqKey = requestKey(request);
cacheResponse = CACHE.get(reqKey);
}
if (cacheResponse)
response = cacheResponse;
// If permanent is true, use the cache first and only go to the network if there is nothing in the cache,
// otherwise, still use cache first, but in the background queue up a network request
if (!cacheResponse)
response = await newRequest(request, cache, fetchOpts);
else if (!permanent) {
newRequest(request, cache, fetchOpts, false);
}
return response!;
}