2025-10-11 13:48:29 +08:00

109 lines
2.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

interface CacheItem<T> {
value: T
expiry?: number // 过期时间戳(毫秒),可选
}
/**
* 通用缓存管理类(支持过期时间,不设 TTL 即为永久缓存)
*/
class CacheManager {
/**
* 设置缓存
* @param key 缓存键
* @param value 缓存值
* @param ttl 过期时间(秒)。若为 undefined、null 或 <=0则视为永久缓存永不过期
*/
static set<T>(key: string, value: T, ttl?: number | null): void {
try {
const cacheItem: CacheItem<T> = { value }
// 仅当 ttl 为正数时才设置过期时间
if (ttl != null && ttl > 0) {
cacheItem.expiry = Date.now() + ttl * 1000
}
// 否则 cacheItem.expiry 保持 undefined表示永久缓存
uni.setStorageSync(key, cacheItem)
}
catch (e) {
console.error('CacheManager.set error:', e)
}
}
/**
* 获取缓存(自动清除过期项)
* @param key 缓存键
* @param defaultValue 默认值(缓存不存在、过期或出错时返回)
* @returns 缓存值或默认值
*/
static get<T>(key: string, defaultValue: T = null as unknown as T): T {
try {
const raw = uni.getStorageSync(key)
if (!raw)
return defaultValue
const cacheItem = raw as CacheItem<T>
// 若有 expiry 且已过期,则清除并返回默认值
if (cacheItem.expiry !== undefined && Date.now() > cacheItem.expiry) {
uni.removeStorageSync(key)
return defaultValue
}
return cacheItem.value
}
catch (e) {
console.error('CacheManager.get error:', e)
return defaultValue
}
}
/**
* 删除指定缓存
*/
static remove(key: string): void {
try {
uni.removeStorageSync(key)
}
catch (e) {
console.error('CacheManager.remove error:', e)
}
}
/**
* 清空所有缓存
*/
static clear(): void {
try {
uni.clearStorageSync()
}
catch (e) {
console.error('CacheManager.clear error:', e)
}
}
/**
* 检查是否存在有效(未过期)缓存
*/
static has(key: string): boolean {
try {
const raw = uni.getStorageSync(key)
if (!raw)
return false
const cacheItem = raw as CacheItem<unknown>
if (cacheItem.expiry !== undefined && Date.now() > cacheItem.expiry) {
uni.removeStorageSync(key)
return false
}
return true
}
catch (e) {
console.error('CacheManager.has error:', e)
return false
}
}
}
export default CacheManager