-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.ts
More file actions
81 lines (67 loc) · 1.67 KB
/
Copy pathcache.ts
File metadata and controls
81 lines (67 loc) · 1.67 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
70
71
72
73
74
75
76
77
78
79
80
81
export interface CacheEntry<T> {
value: T;
expiresAt: number;
}
export class TtlCache<T> {
private store = new Map<string, CacheEntry<T>>();
private maxSize: number;
private defaultTtlMs: number;
constructor(maxSize = 1000, defaultTtlMs = 300000) {
this.maxSize = maxSize;
this.defaultTtlMs = defaultTtlMs;
}
get(key: string): T | undefined {
const entry = this.store.get(key);
if (!entry) return undefined;
if (Date.now() > entry.expiresAt) {
this.store.delete(key);
return undefined;
}
return entry.value;
}
set(key: string, value: T, ttlMs?: number): void {
if (this.store.size >= this.maxSize) {
this.evict();
}
this.store.set(key, {
value,
expiresAt: Date.now() + (ttlMs || this.defaultTtlMs),
});
}
has(key: string): boolean {
return this.store.has(key);
}
delete(key: string): boolean {
return this.store.delete(key);
}
clear(): void {
this.store.clear();
}
get size(): number {
return this.store.size;
}
private evict(): void {
let oldestKey: string = "";
let oldestTime = Infinity;
for (const [key, entry] of this.store) {
if (entry.expiresAt < oldestTime) {
oldestTime = entry.expiresAt;
oldestKey = key;
}
}
if (oldestKey) this.store.delete(oldestKey);
}
}
export function parseCacheControl(header: string): { maxAge: number; noCache: boolean } {
const result = { maxAge: 0, noCache: false };
for (const directive of header.split(",")) {
const trimmed = directive.trim().toLowerCase();
if (trimmed === "no-cache" || trimmed === "no-store") {
result.noCache = true;
}
if (trimmed.startsWith("max-age=")) {
result.maxAge = Number(trimmed.split("=")[1]) * 1000;
}
}
return result;
}