indexedDb模块
快捷操作indexedDb
使用:
// 初始化
let idb=indexDb.new(prop?)
参数:
(可选)
prop={
// 数据库名称
"databaseName": "defaultDB",
// 表格名称
"tableName": "defaultTbl",
// 主键名称
"keyPath": "cacheKey"
}
// 保存
idb.set('id1',{name:'zhangsan',age:'16'})
// 读取
idb.get('id1')
// 搜索
idb.search('name','san','')
参数:
param1: object key 要搜索的对象字段名
param2: object value like 要搜索的对象字段值包含内容(模糊搜索)
param3: primaryKey starts with 要搜索的主键筛选(左匹配), 不限制传''空字符串
--------------------------------
下面正式代码:
/*indexedDB*/ /*20210311 by 284949127*/ /*@author http://mmbro.gitee.com*/ /*@see https://www.cnblogs.com/ljwsyt/p/9760266.html*/ let indexDb = { defaultProp() { return {databaseName: 'defaultDB', tableName: 'defaultTbl', version: undefined, keyPath: 'cacheKey'}; }, new(prop = this.defaultProp()) { let indexDb = { db: null, objectStore: null, request: null, isInit: false, prop: {databaseName: 'defaultDB', tableName: 'defaultTbl', version: undefined, keyPath: 'cacheKey'}, init: async (prop = indexDb.prop) => { if (indexDb.isInit) { console.log('do not init indexedDB again! indexedDB has already Initialized!'); return; } indexDb.prop = prop; const DriverName = 'indexedDB'; if (!globalThis['indexedDB']) { console.log('do not support indexedDB! indexedDB init failed!'); return; } let indexedDB = globalThis[DriverName]; let request = indexedDB.open(indexDb.prop.databaseName, indexDb.prop.version); let isError = false; request.onerror = (event) => { console.log(DriverName + ' open error!', event); isError = true; }; request.onsuccess = (event) => { console.log(DriverName + ' open success!', event); indexDb.db = request.result; }; let p = new Promise((resolve) => { request.onupgradeneeded = function (event) { let db = event.target['result']; // check objectStore name is exist and create objectStore if (!db.objectStoreNames.contains(indexDb.prop.tableName)) { console.log('create objectStore: ' + indexDb.prop.tableName); indexDb.objectStore = db.createObjectStore(indexDb.prop.tableName, {keyPath: indexDb.prop.keyPath}); } indexDb.db = db; resolve(); }; setTimeout(() => resolve(), 500); }); await p; indexDb.request = request; return indexDb.isInit = !isError; }, add: async (cacheKey, obj) => { obj[indexDb.prop.keyPath] = cacheKey; // add if not exist let request = indexDb.db.transaction([indexDb.prop.tableName], 'readwrite') .objectStore(indexDb.prop.tableName) .add(obj); let p = new Promise(((resolve) => { request.onsuccess = function (event) { console.log('add success!', event); resolve(true); }; request.onerror = function (event) { console.log('add failed!', event); resolve(false); } })); return await p; }, get: async (cacheKey) => { let transaction = indexDb.db.transaction([indexDb.prop.tableName]); let objectStore = transaction.objectStore(indexDb.prop.tableName); let request = objectStore.get(cacheKey); let p = new Promise((resolve) => { request.onerror = function (event) { console.log('transaction read failed!', cacheKey, event); resolve(undefined); }; request.onsuccess = function (event) { if (!!request.result) { console.log('transaction read result!', cacheKey, request.result, event); resolve(request.result); } else { console.log('transaction read empty!', cacheKey, event); resolve(undefined); } }; }); let getObj = await p; console.log('getObj is', getObj); return getObj; }, set: async (cacheKey, obj) => { obj[indexDb.prop.keyPath] = cacheKey; // update let request = indexDb.db.transaction([indexDb.prop.tableName], 'readwrite') .objectStore(indexDb.prop.tableName) .put(obj); let p = new Promise((resolve) => { request.onsuccess = function (event) { console.log('transaction update success!cacheKey=', cacheKey, event); resolve(true); }; request.onerror = function (event) { console.log('transaction update failed!', event); resolve(false); }; }); return await p; }, remove: async (cacheKey) => { let request = indexDb.db.transaction([indexDb.prop.tableName], 'readwrite') .objectStore(indexDb.prop.tableName) .delete(cacheKey); let p = new Promise((resolve) => { request.onsuccess = function (event) { console.log('transaction delete success!', event); resolve(true); }; request.onerror = function (event) { console.log('transaction delete failed!', event); resolve(false); }; }); return await p; }, readAll: async () => { let objectStore = indexDb.db.transaction(indexDb.prop.tableName).objectStore(indexDb.prop.tableName); let p = new Promise((resolve) => { let results = {}; objectStore.openCursor().onsuccess = function (event) { let cursor = event.target['result']; if (cursor) { results[cursor.key] = cursor.value; cursor.continue(); } else { console.log('cursor no more object! cursor:', cursor); resolve(results); } }; }); return await p; }, // @link https://www.zhihu.com/question/24227578 search: async (key, value, keyFilter = 'main') => { let all = await indexDb.readAll(); let searchResult = Object.keys(all).filter((oKey) => { let obj = all[oKey]; let oKeyVal = obj[key]; if (!!oKeyVal && oKey.startsWith(keyFilter) && String(oKeyVal).includes(value)) { return true; } }).map((oKey) => all[oKey]); console.log('searchResult', searchResult); return searchResult; }, }; let p = indexDb.init(prop); p.then(() => console.log('indexedDB initialized')); return indexDb; } };