-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathSmartCache.ts
More file actions
69 lines (55 loc) · 1.51 KB
/
SmartCache.ts
File metadata and controls
69 lines (55 loc) · 1.51 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
59
60
61
62
63
64
65
66
67
68
69
import axios from "axios";
const PREFIX = "Scache-";
export class SmartCache {
id: string;
url: string;
constructor(url: string, options?: { includeSearch?: boolean }) {
this.url = url;
if (options?.includeSearch === false) {
const u = new URL(url);
this.id = u.protocol + u.host + u.pathname;
} else {
this.id = url;
}
}
private save(response: any) {
localStorage.setItem(
PREFIX + this.id,
JSON.stringify({
url: this.url,
data: response.data,
eTag: response.headers["etag"],
lastModified: response.headers["last-modified"],
}),
);
}
async get() {
const cache = localStorage.getItem(PREFIX + this.id);
// If it has never been cached, send the request right away
if (cache === null) {
const response = await axios.get(this.url);
// Cache response in local storage
this.save(response);
return response.data;
}
const parsed = JSON.parse(cache);
const headers: Record<string, string> = {};
if (parsed.eTag) {
headers["If-None-Match"] = parsed.eTag;
} else if (parsed.lastModified) {
headers["If-Modified-Since"] = parsed.lastModified;
}
const response = await axios.get(this.url, {
headers,
validateStatus(status) {
return status === 304 || (status >= 200 && status < 300);
},
});
if (response.status === 304) {
return parsed.data;
} else {
this.save(response);
return response.data;
}
}
}