forked from
npmx.dev/npmx.dev
[READ-ONLY]
a fast, modern browser for the npm registry
1/**
2 * Local cache data entry
3 */
4interface LocalCachedEntry<T = unknown> {
5 value: T
6 ttl?: number
7 cachedAt: number
8}
9
10/**
11 * Checks to see if a cache entry is stale locally
12 * @param entry - The entry from the locla cache
13 * @returns
14 */
15function isCacheEntryStale(entry: LocalCachedEntry): boolean {
16 if (!entry.ttl) return false
17 const now = Date.now()
18 const expiresAt = entry.cachedAt + entry.ttl * 1000
19 return now > expiresAt
20}
21
22/**
23 * Local implmentation of a cache to be used during development
24 */
25export class LocalCacheAdapter implements CacheAdapter {
26 private readonly storage = useStorage('atproto:generic')
27
28 async get<T>(key: string): Promise<T | undefined> {
29 const result = await this.storage.getItem<LocalCachedEntry<T>>(key)
30 if (!result) return
31 if (isCacheEntryStale(result)) {
32 await this.storage.removeItem(key)
33 return
34 }
35 return result.value
36 }
37
38 async set<T>(key: string, value: T, ttl?: number): Promise<void> {
39 await this.storage.setItem(key, { value, ttl, cachedAt: Date.now() })
40 }
41
42 async delete(key: string): Promise<void> {
43 await this.storage.removeItem(key)
44 }
45}