-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.ts
79 lines (64 loc) · 1.97 KB
/
storage.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
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
import { Storage } from "~node_modules/@plasmohq/storage"
const storage = new Storage()
const MAX_CACHE_SIZE = 500 // Max number of items in the cache
const cache = new Map<string, string>() // LRU cache
async function loadCache() {
const storedCache = await storage.get("kagiSummarizerCache")
if (storedCache) {
const entries = Object.entries(storedCache)
for (const [key, value] of entries) {
cache.set(key, value)
}
}
}
// Save the cache to storage
async function saveCache() {
const cacheObj: { [key: string]: string } = {}
for (const [key, value] of cache) {
cacheObj[key] = value
}
await storage.set("kagiSummarizerCache", cacheObj)
}
// Clear the cache
async function clearCache() {
cache.clear()
await storage.remove("kagiSummarizerCache")
}
// Initialize the cache
loadCache()
async function getCachedData(key: string): Promise<string | undefined> {
const cachedData = cache.get(key)
if (cachedData) {
console.log(`using cached summary for ${key}`)
return cachedData
}
const storedData = await storage.get(key)
if (storedData) {
console.log(`using cached summary for ${key} from storage`)
// Add to the in-memory cache
cache.set(key, storedData)
// Remove the oldest item if the cache size exceeds the max size
if (cache.size > MAX_CACHE_SIZE) {
const oldestKey = cache.keys().next().value
cache.delete(oldestKey)
await storage.remove(oldestKey)
}
return storedData
}
return undefined
}
async function setCachedData(key: string, value: string): Promise<void> {
// Add to the in-memory cache
cache.set(key, value)
// Store in local storage
await storage.set(key, value)
saveCache()
// Remove the oldest item if the cache size exceeds the max size
if (cache.size > MAX_CACHE_SIZE) {
const oldestKey = cache.keys().next().value
cache.delete(oldestKey)
await storage.remove(oldestKey)
}
}
export { clearCache, getCachedData, setCachedData }
export default storage