主题
基于localforage的浏览器存储INDEXEDDB的使用
一、指定storeName,一般用于存储业务数据
1)创建Storage
javascript
import { createLocalforage } from 'lonbon-common/lib/db.js'
window.accountStorage = createLocalforage({
name: 'Business stroage',
storeName: 'accountId:' + sessionStorage.accountId
})
2)使用Storage
javascript
window.accountStorage.setItem("tabActive", val) //存
let tabs = await window.accountStorage.getItem("tabs") //取
3)示例
二、不指定storeName,一般用于按日期存储的日志数据
1)创建Storage
javascript
import { createLocalforage } from 'lonbon-common/lib/db.js'
window.businessStorage = createLocalforage({
name: 'Business stroage'
})
2)使用Storage,固定Key值,Key值+日期将作为storeName
javascript
window.businessStorage.setItem("PushAlarm", val) //存
3)示例
三、关于createLocalforage
javascript
import moment from 'moment/moment'
import localforage from 'localforage'
import UUID from 'uuidjs'
/**
* 若构造函数传了storeName,则固定store
* 若没传则setItem的key为storeName,即动态生成store
*/
export class webDB {
constructor({ name, storeName, expire = 7 }) {
this.name = name;
this.storeName = storeName;
this.expire = expire;
this.index = 0;
this.createStore()
}
createStore() {
if(!this.storeName) return
this.store = localforage.createInstance({
name: this.name,
storeName: this.storeName,
driver: localforage.INDEXEDDB
})
}
setItem(key, val) {
if(this.store) {
this.store.setItem(key, val)
return
}
let store = localforage.createInstance({
name: this.name,
storeName: key + String(moment().format("YYYYMMDD")),
driver: localforage.INDEXEDDB
})
store.setItem(`${moment().format("HH:mm:ss")}_${++this.index}`, val)
}
removeItem(key) {
if(this.store) {
this.store.removeItem(key)
}
}
async getItem(key) {
if(this.store) {
return await this.store.getItem(key)
}
return null
}
async getAllItem() {
let result = []
if(this.store) {
await this.store.iterate((value, key, iterationNumber) => {
result.push({value, key})
})
}
return result
}
}
export function createLocalforage(options) {
return new webDB(options)
}