-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathTimeCache.ts
More file actions
57 lines (46 loc) · 1.34 KB
/
TimeCache.ts
File metadata and controls
57 lines (46 loc) · 1.34 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
import dayjs from "dayjs";
const PREFIX = "Tcache-";
export class TimeCache<T> {
private name: string;
/** Unix timestamp of when the cache should expire */
private expiry: number;
/**
* @param name The name of the cache. Must be unique
* @param lifetime The number of seconds the cache should live for before being invalidated
*/
constructor(
name: string,
lifetime: number,
options?: { includeSearch?: boolean },
) {
if (options?.includeSearch || options?.includeSearch === undefined) {
const url = new URL(name);
this.name = url.protocol + url.host + url.pathname;
} else {
this.name = name;
}
this.expiry = dayjs().add(lifetime, "seconds").unix();
}
/** Will return the cached value, or null if expired, or undefined if the cache item doesn't exist. */
get(): T | null | undefined {
const cache = localStorage.getItem(PREFIX + this.name);
if (cache === null) {
return undefined;
}
const parsed = JSON.parse(cache);
// If expired, return null
if (dayjs().unix() > parsed.expiry) {
return null;
}
return parsed.data;
}
delete(): void {
return localStorage.removeItem(PREFIX + this.name);
}
store(value: any) {
localStorage.setItem(
PREFIX + this.name,
JSON.stringify({ data: value, expiry: this.expiry }),
);
}
}