1、封装一个indexedDB的使用类库(CreateDB)
// business database
const dbMap = {
defaultDBName: "local_basic_db"
};
// Database default storage space (database table)
let defaultDBTable = "basic_table";
// default database version
let defaultVersion = 1;
class CreateDB {
constructor (config = {}) {
let dbName = config?.dbName || dbMap.defaultDBName;
let dbTable = config?.dbTable || defaultDBTable;
this.isInit = false;
this.dbName = dbName;
this.version = defaultVersion;
this.dbTable = dbTable;
this.databases = [];
this.initPromise = this.initialization();
}
// initialization
async initialization() {
const database = await this.checkDB({ dbName: this.dbName });
if (window.indexedDB?.databases) {
if (database) {
this.version = database.version;
}
} else {
const version = await new Promise((resolve, reject) => {
const indexedDB = window.indexedDB.open(this.dbName);
indexedDB.onupgradeneeded = (event) => {
console.log("verson indexedDB onupgradeneeded", event);
const db = event.target.result;
const version = db.version;
db.close();
resolve(version);
};
indexedDB.onsuccess = async(event) => {
console.log("verson indexedDB onsuccess", event);
const db = event.target.result;
const version = db.version;
db.close();
resolve(version);
};
indexedDB.onerror = (event) => {
console.log("verson indexedDB onerror", event);
reject();
};
}).catch(err => {
console.log("verson indexedDB error", err);
});
version && (this.version = version);
}
console.log("Initialization completed", database);
this.isInit = true;
}
async initializationWait() {
if (!this.isInit) {
await this.initPromise;
}
}
// Connect to the database
openDB() {
const db = window.indexedDB.open(this.dbName, this.version);
return db;
}
// Get all databases under the browser
async getDBS() {
const res = await window.indexedDB.databases().catch(() => {
return [];
});
this.databases = res;
return res;
}
// Check if the specified database exists
async checkDB({ dbName }) {
if (dbName) {
const databaseList = await this.getDBS();
if (databaseList.length) {
let database;
for (let i = 0; i < databaseList.length; i++) {
let curr = databaseList[i];
if (curr.name === dbName) {
database = curr;
break;
}
}
return database;
}
}
return null;
}
// Check if the storage space exists
checkTable({ db, dbTable }) {
const objectStoreNames = db.objectStoreNames;
return objectStoreNames.contains(dbTable);
}
// Data addition method
async add({ db, dbTable, name, value }) {
async function handleAdd(resolve) {
const transaction = db.transaction([dbTable], 'readwrite');
const objectStore = transaction.objectStore(dbTable);
// written as key-value pairs
const updateRequest = objectStore.put(value, name);
updateRequest.onsuccess = (event) => {
console.log("Data set successfully", event);
resolve(true);
};
updateRequest.onerror = (event) => {
console.log("Data setting failed", event);
resolve();
};
};
return new Promise(resolve => handleAdd(resolve)).catch(err => {
console.log("Data setting error", err);
return false;
});
}
// Data acquisition method
async get({ db, dbTable, name }) {
return new Promise(resolve => {
const isExistTable = this.checkTable({ db, dbTable });
// Determine whether storage space exists
if (isExistTable) {
// Exist, get and return the specified key value
const transaction = db.transaction([dbTable], 'readonly');
const objectStore = transaction.objectStore(dbTable);
const getRequest = objectStore.get(name);
getRequest.onsuccess = (event) => {
console.log("Data obtained successfully", event);
const data = event.target.result;
resolve(data);
};
getRequest.onerror = (event) => {
console.log("Data acquisition failed", event);
resolve();
};
} else {
resolve();
}
}).catch(err => {
console.log("Data acquisition error", err);
});
}
// add storage
async addDBTable({ dbTable, name, value }) {
return new Promise((resolve, reject) => {
this.version = this.version + 1;
const indexedDB = this.openDB();
indexedDB.onupgradeneeded = (event) => {
console.log("add table indexedDB onupgradeneeded", event);
const db = event.target.result;
if (!db.objectStoreNames.contains(dbTable)) {
db.createObjectStore(dbTable);
}
};
indexedDB.onsuccess = async (event) => {
console.log("add table indexedDB onsuccess", event);
const db = event.target.result;
this.version = db.version;
const res = await this.add({ db, dbTable, name, value });
db.close();
resolve(res);
};
indexedDB.onerror = (event) => {
console.log("add table indexedDB onerror", event);
const db = event.target.result;
this.version = db.version;
reject();
};
}).catch(err => {
console.log("add table indexedDB error", err);
return false;
});
}
// clear storage
async clearDBTable({ dbTable }) {
return new Promise((resolve, reject) => {
this.version = this.version + 1;
const indexedDB = this.openDB();
indexedDB.onupgradeneeded = (event) => {
console.log("clear table indexedDB onupgradeneeded", event);
const db = event.target.result;
if (db.objectStoreNames.contains(dbTable)) {
db.deleteObjectStore(dbTable);
}
};
indexedDB.onsuccess = async (event) => {
console.log("clear table indexedDB onsuccess", event);
const db = event.target.result;
this.version = db.version;
db.close();
resolve(true);
};
indexedDB.onerror = (event) => {
console.log("clear table indexedDB onerror", event);
const db = event.target.result;
this.version = db.version;
reject();
};
}).catch(err => {
console.log("clear table indexedDB error", err);
return false;
});
}
// retrieve data
async getItem(config) {
await this.initializationWait();
return new Promise((resolve, reject) => {
const {
name,
dbTable: incomingDBTable
} = config || {};
const indexedDB = this.openDB();
indexedDB.onsuccess = async (event) => {
console.log("get indexedDB onsuccess", event);
const db = event.target.result;
let dbTable = incomingDBTable;
// Determine whether there is incoming storage space
if (dbTable) {
// Yes, data acquisition is performed directly in the incoming storage space
const res = await this.get({ db, dbTable, name });
db.close();
return resolve(res);
}
// None, get data in the default storage space
dbTable = this.dbTable;
const res = await this.get({ db, dbTable, name });
db.close();
resolve(res);
}
indexedDB.onerror = (event) => {
console.log("get indexedDB onerror", event);
reject();
}
}).catch(err => {
console.log("get indexedDB error", err);
});
}
// Add/update data
async setItem(config) {
await this.initializationWait();
return new Promise((resolve, reject) => {
const {
name,
value,
dbTable: incomingDBTable
} = config || {};
const indexedDB = this.openDB();
const dbTable = incomingDBTable || this.dbTable;
indexedDB.onsuccess = async (event) => {
console.log("set indexedDB onsuccess", event);
const db = event.target.result;
const isExistTable = this.checkTable({ db, dbTable });
let res;
// Determine whether the specified storage space exists
if (isExistTable) {
// There is a direct add or update
res = await this.add({ db, dbTable, name, value });
db.close();
} else {
db.close();
res = await this.addDBTable({ dbTable, name, value });
}
resolve(res);
}
indexedDB.onerror = (event) => {
console.log("set indexedDB onerror", event);
reject();
}
}).catch(err => {
console.log("set indexedDB error", err);
return false;
});
}
// Clear the specified data in the specified storage space under the database
async removeItem(config) {
await this.initializationWait();
return new Promise((resolve, reject) => {
const {
name,
dbTable: incomingDBTable
} = config || {};
const indexedDB = this.openDB();
const dbTable = incomingDBTable || this.dbTable;
indexedDB.onsuccess = (event) => {
console.log("remove indexedDB onsuccess", event);
const db = event.target.result;
const isExistTable = this.checkTable({ db, dbTable });
// Determine whether the specified storage space exists
if (isExistTable) {
const deleteTransaction = db.transaction([dbTable], 'readwrite');
const deleteObjectStore = deleteTransaction.objectStore(dbTable);
const deleteRequest = deleteObjectStore.delete(name);
deleteRequest.onsuccess = (event) => {
console.log("Data removed successfully", event);
db.close();
resolve(true);
};
deleteRequest.onerror = (event) => {
console.log("Data removal failed", event);
db.close();
resolve(false);
};
} else {
db.close();
resolve(true);
}
}
indexedDB.onerror = (event) => {
console.log("remove indexedDB onerror", event);
reject();
}
}).catch(err => {
console.log("remove indexedDB error", err);
return false;
});
}
// Clear all data in the specified storage space under the database
async clear(config) {
await this.initializationWait();
return new Promise((resolve, reject) => {
const {
dbTable: incomingDBTable
} = config || {};
const indexedDB = this.openDB();
const dbTable = incomingDBTable || this.dbTable;
indexedDB.onsuccess = (event) => {
console.log("clear indexedDB onsuccess", event);
const db = event.target.result;
const isExistTable = this.checkTable({ db, dbTable });
if (isExistTable) {
const transaction = db.transaction([dbTable], 'readwrite');
const objectStore = transaction.objectStore(dbTable);
const cursorRequest = objectStore.openCursor();
cursorRequest.onsuccess = (event) => {
let cursor = event.target.result;
if (cursor) {
cursor.delete();
cursor.continue();
}
};
cursorRequest.onerror = (event) => {
console.log("Data clearing failed", event);
db.close();
resolve(false);
};
transaction.oncomplete = (event) => {
console.log("Data cleared successfully", event);
db.close();
resolve(true);
};
transaction.onerror = (event) => {
console.log("Data clearing transaction succeeded", event);
db.close();
resolve(false);
};
} else {
db.close();
resolve(true);
}
}
indexedDB.onerror = (event) => {
console.log("clear indexedDB onerror", event);
reject();
}
}).catch(err => {
console.log("clear indexedDB error", err);
return false;
});
}
// Clear the specified storage space under the database
async clearTableItem(config) {
await this.initializationWait();
return new Promise((resolve, reject) => {
const {
dbTable: incomingDBTable
} = config || {};
const indexedDB = this.openDB();
const dbTable = incomingDBTable || this.dbTable;
indexedDB.onsuccess = async (event) => {
console.log("clear table indexedDB onsuccess", event);
const db = event.target.result;
const isExistTable = this.checkTable({ db, dbTable });
if (isExistTable) {
db.close();
const res = await this.clearDBTable({ dbTable });
resolve(res);
} else {
db.close();
resolve(true);
}
}
indexedDB.onerror = (event) => {
console.log("clear table indexedDB onerror", event);
reject();
}
}).catch(err => {
console.log("clear table indexedDB error", err);
return false;
});
}
}
export { CreateDB };
export { dbMap };
export default {
CreateDB,
dbMap
};
2、内容说明
- dbMap:用来记录存储数据库的名称,放在此处集中管理数据的名称;
- defaultDBTable:每个数据库默认的存储空间(相当于默认表);
- defaultVersion:每个数据库默认的版本(都是从1开始);
- CreateDB:给予传入的数据库名称、存储空间,生成一个数据库的对象,用来操作该数据库。不传入,就都是用默认值;
- initialization:在new一个数据库的实例是,会自动执行的初始化方法。主要是用来检查当下浏览器的数据库中是否存在构造的数据库,如果存在,则记录该数据库的当下版本,以便之后连接数据库时使用;
- openDB:连接数据库;
- getDBS:获取浏览器当下存在的数据库;
- checkDB:检查浏览器是否存在构造的数据库;
- checkTable:在构造的数据库中,检查是否存在指定的存储空间;
- add:以键值对的形式添加数据;
- get:通过键获取数据;
- addDBTable:添加存储空间;
- clearDBTable:移除某个存储空间;
- getItem:用来获取数据(对外实际使用的数据操作方法);
- setItem:添加或是更新数据(对外实际使用的数据操作方法);
- removeItem:移除数据(对外实际使用的数据操作方法);
- clear:移除某个存储空间下的所有数据(对外实际使用的数据操作方法);
- clearTableItem:移除某个存储空间(对外实际使用的数据操作方法);
注意:都是异步方法;文章来源:https://www.toymoban.com/news/detail-516416.html
3、使用文章来源地址https://www.toymoban.com/news/detail-516416.html
const currDB = new CreateDB();
// 或是:const currDB = new CreateDB({ dbName: dbMap.defaultDBName });
// 获取
currDB.getItem({ name: "key" });
// 添加或更新
currDB.setItem({ name: "key", value: 123456 });
// 移除
currDB.removeItem({ name: "key" });
// 清除某个存储空间下的所有数据
currDB.clear({ dbTable: "dbTable" });
// 清除某个存储空间
currDB.clearTableItem({ dbTable: "dbTable" });
到了这里,关于indexeddb 二次封装的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!