166 lines
2.9 KiB
JavaScript
166 lines
2.9 KiB
JavaScript
/**
|
|
* 本地存储管理器
|
|
* 提供统一的数据存储接口和错误处理
|
|
*/
|
|
|
|
class Storage {
|
|
/**
|
|
* 设置数据
|
|
*/
|
|
static set(key, data) {
|
|
try {
|
|
wx.setStorageSync(key, data)
|
|
return { success: true }
|
|
} catch (e) {
|
|
console.error(`存储失败 [${key}]:`, e)
|
|
return { success: false, error: e }
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 获取数据
|
|
*/
|
|
static get(key, defaultValue = null) {
|
|
try {
|
|
const data = wx.getStorageSync(key)
|
|
return data || defaultValue
|
|
} catch (e) {
|
|
console.error(`读取失败 [${key}]:`, e)
|
|
return defaultValue
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 删除数据
|
|
*/
|
|
static remove(key) {
|
|
try {
|
|
wx.removeStorageSync(key)
|
|
return { success: true }
|
|
} catch (e) {
|
|
console.error(`删除失败 [${key}]:`, e)
|
|
return { success: false, error: e }
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 清空所有数据
|
|
*/
|
|
static clear() {
|
|
try {
|
|
wx.clearStorageSync()
|
|
return { success: true }
|
|
} catch (e) {
|
|
console.error('清空存储失败:', e)
|
|
return { success: false, error: e }
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 获取存储信息
|
|
*/
|
|
static getInfo() {
|
|
try {
|
|
return wx.getStorageInfoSync()
|
|
} catch (e) {
|
|
console.error('获取存储信息失败:', e)
|
|
return null
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 批量设置
|
|
*/
|
|
static setMultiple(items) {
|
|
const results = []
|
|
for (const [key, value] of Object.entries(items)) {
|
|
results.push(this.set(key, value))
|
|
}
|
|
return results
|
|
}
|
|
|
|
/**
|
|
* 批量获取
|
|
*/
|
|
static getMultiple(keys, defaultValue = null) {
|
|
const result = {}
|
|
keys.forEach(key => {
|
|
result[key] = this.get(key, defaultValue)
|
|
})
|
|
return result
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 数据同步管理器
|
|
* 处理本地和云端数据同步
|
|
*/
|
|
class SyncManager {
|
|
constructor() {
|
|
this.syncQueue = []
|
|
this.isSyncing = false
|
|
}
|
|
|
|
/**
|
|
* 添加到同步队列
|
|
*/
|
|
addToQueue(type, data) {
|
|
this.syncQueue.push({
|
|
type,
|
|
data,
|
|
timestamp: Date.now()
|
|
})
|
|
this.processQueue()
|
|
}
|
|
|
|
/**
|
|
* 处理同步队列
|
|
*/
|
|
async processQueue() {
|
|
if (this.isSyncing || this.syncQueue.length === 0) {
|
|
return
|
|
}
|
|
|
|
this.isSyncing = true
|
|
|
|
while (this.syncQueue.length > 0) {
|
|
const item = this.syncQueue.shift()
|
|
try {
|
|
await this.syncItem(item)
|
|
} catch (e) {
|
|
console.error('同步失败:', e)
|
|
// 重新加入队列
|
|
this.syncQueue.push(item)
|
|
break
|
|
}
|
|
}
|
|
|
|
this.isSyncing = false
|
|
}
|
|
|
|
/**
|
|
* 同步单个项目
|
|
*/
|
|
async syncItem(item) {
|
|
// TODO: 实现云端同步逻辑
|
|
console.log('同步数据:', item)
|
|
return new Promise((resolve) => {
|
|
setTimeout(resolve, 100)
|
|
})
|
|
}
|
|
|
|
/**
|
|
* 获取待同步数量
|
|
*/
|
|
getPendingCount() {
|
|
return this.syncQueue.length
|
|
}
|
|
}
|
|
|
|
const syncManager = new SyncManager()
|
|
|
|
module.exports = {
|
|
Storage,
|
|
syncManager
|
|
}
|