-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.ts
43 lines (38 loc) · 1.08 KB
/
utils.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
export function isBrowser() {
return typeof window !== "undefined";
}
// Helpers
export function isValidURL(str: string) {
try {
return !!new URL(str);
} catch (e) {
return false;
}
}
export function getCircularReplacer() {
const seen = new WeakSet();
return (_key: string, value: any) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) return;
seen.add(value);
}
return value;
};
}
export function makeKey(key: string, namespace: string = "keyv-cache") {
const decodedKey = decodeURIComponent(key);
return isValidURL(decodedKey)
? decodedKey
: `${location.origin}?key=${decodedKey}&ns=${namespace}`;
}
export function isValidKey(keyRes: Response) {
const now = Date.now();
const timestamp = keyRes.headers.get("timestamp") || now;
const ttl = keyRes.headers.get("ttl") || 0;
return +ttl + +timestamp >= now;
}
export function makeResponse(result: any, ttl: number) {
return new Response(JSON.stringify(result, getCircularReplacer()), {
headers: { timestamp: `${Date.now()}`, ttl: `${ttl}` },
});
}