cache.js
1.52 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
// 查询结果缓存 - 服务端内存缓存,用于二次查找和分页
const cache = new Map()
// 缓存过期时间(毫秒),默认30分钟
const CACHE_TTL = 30 * 60 * 1000
// 定时清理过期缓存
setInterval(() => {
const now = Date.now()
for (const [key, value] of cache) {
if (now - value.createdAt > CACHE_TTL) {
cache.delete(key)
}
}
}, 60 * 1000)
// 存储查询结果
export function setCache(queryId, data) {
cache.set(queryId, {
data,
columns: Object.keys(data[0] || {}),
createdAt: Date.now(),
totalCount: data.length,
})
}
// 获取缓存的查询结果
export function getCache(queryId) {
const entry = cache.get(queryId)
if (!entry) return null
if (Date.now() - entry.createdAt > CACHE_TTL) {
cache.delete(queryId)
return null
}
return entry
}
// 在缓存中二次查找
export function searchInCache(queryId, keyword) {
const entry = getCache(queryId)
if (!entry) return null
if (!keyword || keyword.trim() === '') {
return entry
}
const lowerKeyword = keyword.toLowerCase()
const filtered = entry.data.filter(row =>
entry.columns.some(col => {
const val = row[col]
if (val === null || val === undefined) return false
return String(val).toLowerCase().includes(lowerKeyword)
})
)
return {
...entry,
data: filtered,
totalCount: filtered.length,
}
}
// 删除缓存
export function deleteCache(queryId) {
cache.delete(queryId)
}
// 清理所有缓存
export function clearAllCache() {
cache.clear()
}