-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgithub-cache.js
More file actions
58 lines (45 loc) · 1.37 KB
/
github-cache.js
File metadata and controls
58 lines (45 loc) · 1.37 KB
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
// This file is use to cached GitHub api reponse for end user in thier browser
// so we can save github api calls & not hit rate-limiting.
const CACHE_PREFIX = "passcodes_cache_";
const DEFAULT_TTL = 1000 * 60 * 60 * 6; // 6 hours
export async function githubAPIFetch({
cacheKey,
routeURI,
ttl = DEFAULT_TTL,
}) {
const key = CACHE_PREFIX + cacheKey;
const url = `https://api.github.com/${routeURI}`;
try {
const cached = localStorage.getItem(key);
if (cached) {
const parsed = JSON.parse(cached);
if (parsed.timestamp && Date.now() - parsed.timestamp < ttl) {
return parsed.data;
}
}
} catch (err) {
console.warn(`Failed reading cache "${cacheKey}"`, err);
}
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
const data = await response.json();
localStorage.setItem(
key,
JSON.stringify({
timestamp: Date.now(),
data,
}),
);
return data;
} catch (err) {
console.error(`Fetch failed for ${url}`, err);
const cached = localStorage.getItem(key);
if (cached) {
return JSON.parse(cached).data;
}
throw err;
}
}