-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathcache.ts
More file actions
43 lines (37 loc) · 970 Bytes
/
cache.ts
File metadata and controls
43 lines (37 loc) · 970 Bytes
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
interface CacheEntry {
value: unknown;
expires: number;
}
const DEFAULT_TTL = 5 * 60 * 1000;
const MAX_ENTRIES = 200;
const cache = new Map<string, CacheEntry>();
function evictExpired(): void {
const now = Date.now();
cache.forEach((entry, key) => {
if (now > entry.expires) {
cache.delete(key);
}
});
}
export function getCached<T>(key: string): T | null {
const entry = cache.get(key);
if (!entry) return null;
if (Date.now() > entry.expires) {
cache.delete(key);
return null;
}
return entry.value as T;
}
export function setCache(key: string, value: unknown, ttl = DEFAULT_TTL): void {
if (cache.size >= MAX_ENTRIES) {
evictExpired();
}
if (cache.size >= MAX_ENTRIES) {
const oldestKey = cache.keys().next().value;
if (oldestKey) cache.delete(oldestKey);
}
cache.set(key, { value, expires: Date.now() + ttl });
}
export function tokenPrefix(token: string): string {
return token.slice(0, 8);
}