UNPKG

@10yun/cv-js-utils

Version:

常用 js-utils 工具类库

103 lines (92 loc) 2.81 kB
import localforage from 'localforage/src/localforage.js'; /** * ============================================================================= * ***************************** localForage ****************************** * ============================================================================= */ class StorageIndexDB { constructor(options) { this.db_name = options.db_name || 'cvjs'; localforage.config({ name: this.db_name, storeName: 'common' }); /** * 缓存的key */ this.keyExpired = {}; this.keyGroup = []; this.__open_log = false; this.__timer = {}; } async idbTest() { try { if (cvUtils.isDevice_ios()) { await localforage.setItem('__test__', $A.Time()); } this.__open_log && console.log('IDBTest OK'); } catch (error) { if (this.__open_log) { console.error('IDBTest Error: ', error); ElMessageBox.alert(error.message, '温馨提示', { // autofocus: false, confirmButtonText: 'OK' }).then(() => { $A.reloadUrl(); }); } else { $A.reloadUrl(); } } } idbSave(key, value, delay = 100) { if (typeof this.__timer[key] !== 'undefined') { clearTimeout(this.__timer[key]); delete this.__timer[key]; } this.__timer[key] = setTimeout(async (_) => { // console.log('---idbSave--', key, value); let parseValue = JSON.parse(JSON.stringify(value)); await localforage.setItem(key, parseValue); }, delay); } idbGetItem(key) { return localforage.getItem(key); } idbSetItem(key, value) { // console.log('---idbSetItem--', key, value); let parseValue = ''; if (value && value != 'undefined') { parseValue = JSON.parse(JSON.stringify(value)); } return localforage.setItem(key, parseValue); } idbDelItem(key) { // return localforage.removeItem(key); localforage.removeItem(key).then((_) => {}); } idbClear() { return localforage.clear(); } async idbGetString(key, def = '') { const value = await this.idbGetItem(key); return typeof value === 'string' || typeof value === 'number' ? value : def; } async idbGetInt(key, def = 0) { const value = await this.idbGetItem(key); return typeof value === 'number' ? value : def; } async idbGetBoolean(key, def = false) { const value = await this.idbGetItem(key); return typeof value === 'boolean' ? value : def; } async idbGetArray(key, def = []) { const value = await this.idbGetItem(key); return cvUtils.isTypeArray(value) ? value : def; } async idbGetJson(key, def = {}) { const value = await this.idbGetItem(key); return cvUtils.isTypeJson(value) ? value : def; } } export default StorageIndexDB;