90 lines
2.2 KiB
TypeScript
90 lines
2.2 KiB
TypeScript
import AsyncStorage from '@react-native-async-storage/async-storage'
|
|
|
|
import { APP_VERSION } from '@/app.config'
|
|
|
|
interface StorageData {
|
|
[key: string]: string
|
|
}
|
|
|
|
class Storage {
|
|
private readonly STORAGE_KEY = `app_storage_${APP_VERSION}`
|
|
private cache: StorageData = {}
|
|
private isInitialized = false
|
|
|
|
// 初始化存储,从本地存储加载
|
|
private async init() {
|
|
if (this.isInitialized) return
|
|
|
|
try {
|
|
const storedData = await AsyncStorage.getItem(this.STORAGE_KEY)
|
|
if (storedData) {
|
|
this.cache = JSON.parse(storedData)
|
|
}
|
|
} catch (error) {
|
|
console.warn('初始化存储失败:', error)
|
|
this.cache = {}
|
|
}
|
|
|
|
this.isInitialized = true
|
|
}
|
|
|
|
// 获取存储值
|
|
async get<T>(key: string): Promise<T | null> {
|
|
try {
|
|
await this.init()
|
|
|
|
const value = this.cache[key]
|
|
return value as unknown as T
|
|
// console.log('get-----------', value)
|
|
} catch (error) {
|
|
return null
|
|
}
|
|
}
|
|
|
|
// 设置存储
|
|
async set(key: string, value: any): Promise<void> {
|
|
try {
|
|
await this.init()
|
|
|
|
this.cache[key] = value
|
|
|
|
// 保存到本地存储
|
|
await AsyncStorage.setItem(this.STORAGE_KEY, JSON.stringify(this.cache))
|
|
// console.log('💾 已存储:', key, '->', value)
|
|
} catch (error) {
|
|
console.warn('保存存储失败:', error)
|
|
}
|
|
}
|
|
|
|
// 清理所有存储
|
|
async clear(): Promise<void> {
|
|
this.cache = {}
|
|
try {
|
|
await AsyncStorage.removeItem(this.STORAGE_KEY)
|
|
console.log('🗑️ 已清理所有存储')
|
|
} catch (error) {
|
|
console.warn('清理存储失败:', error)
|
|
}
|
|
}
|
|
}
|
|
|
|
// 导出单例实例
|
|
export const storage = new Storage()
|
|
|
|
// 为了向后兼容,保留原来的视频缓存接口
|
|
export const videoUrlCache = {
|
|
async get(originalUrl: string, width: number = 256): Promise<string | null> {
|
|
const key = `video_${originalUrl}_${width}`
|
|
return await storage.get(key)
|
|
},
|
|
|
|
async set(originalUrl: string, finalUrl: string, width: number = 256): Promise<void> {
|
|
const key = `video_${originalUrl}_${width}`
|
|
await storage.set(key, finalUrl)
|
|
},
|
|
|
|
async clear(): Promise<void> {
|
|
await storage.clear()
|
|
},
|
|
}
|