109 lines
2.5 KiB
TypeScript
Raw Normal View History

2025-10-11 13:48:29 +08:00
interface CacheItem<T> {
value: T
expiry?: number // 过期时间戳(毫秒),可选
}
/**
* TTL
*/
class CacheManager {
/**
*
* @param key
* @param value
* @param ttl undefinednull <=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