提供两种方法来存储具有相同 ID 的多条记录:
- 数组存储方式:
-
优点:
-
所有相关记录存储在同一个键下,便于管理
-
读取操作更快,只需要一次 getItem 调用
-
缺点:
-
每次添加新记录都需要读取和写入整个数组
-
如果数组很大,可能会影响性能
- 复合键存储方式:
-
优点:
-
每条记录独立存储,写入操作更高效
-
更适合大量数据的情况
-
缺点:
-
读取所有记录需要遍历所有键
-
需要额外的键管理逻辑
import localforage from 'localforage'
// 方案1: 使用数组存储同一ID的多条记录
export async function addRecordToArray(id: string, data: any) {
try {
// 获取现有记录数组,如果不存在则创建新数组
const existingRecords = await localforage.getItem<any[]>(`records-${id}`) || []
// 添加新记录到数组
existingRecords.push({
...data,
timestamp: Date.now()
})
// 保存更新后的数组
await localforage.setItem(`records-${id}`, existingRecords)
return true
} catch (error) {
console.error('Error adding record:', error)
return false
}
}
// 方案2: 使用复合键存储记录
export async function addRecordWithCompositeKey(id: string, data: any) {
try {
const timestamp = Date.now()
const compositeKey = `${id}-${timestamp}`
await localforage.setItem(compositeKey, {
...data,
timestamp
})
return true
} catch (error) {
console.error('Error adding record:', error)
return false
}
}
// 获取指定ID的所有记录(数组方式)
export async function getRecordsByIdFromArray(id: string) {
try {
const records = await localforage.getItem<any[]>(`records-${id}`)
return records || []
} catch (error) {
console.error('Error getting records:', error)
return []
}
}
// 获取指定ID的所有记录(复合键方式)
export async function getRecordsByIdFromCompositeKeys(id: string) {
try {
const records: any[] = []
// 遍历所有键以找到匹配的记录
await localforage.iterate((value, key) => {
if (key.startsWith(`${id}-`)) {
records.push(value)
}
})
// 按时间戳排序
return records.sort((a, b) => b.timestamp - a.timestamp)
} catch (error) {
console.error('Error getting records:', error)
return []
}
}