71 lines
1.8 KiB
JavaScript
71 lines
1.8 KiB
JavaScript
const KeyValueDB = {
|
||
dbName: 'kvStorage',
|
||
storeName: 'kvStore',
|
||
|
||
async init() {
|
||
return new Promise((resolve) => {
|
||
const request = indexedDB.open(this.dbName, 1);
|
||
|
||
request.onupgradeneeded = (e) => {
|
||
const db = e.target.result;
|
||
if (!db.objectStoreNames.contains(this.storeName)) {
|
||
db.createObjectStore(this.storeName);
|
||
}
|
||
};
|
||
|
||
request.onsuccess = () => resolve(request.result);
|
||
});
|
||
},
|
||
|
||
// 设置值(类似 localStorage.setItem)
|
||
async set(key, value) {
|
||
const db = await this.init();
|
||
return new Promise((resolve) => {
|
||
const tx = db.transaction(this.storeName, 'readwrite');
|
||
tx.objectStore(this.storeName).put(value, key);
|
||
tx.oncomplete = () => resolve();
|
||
});
|
||
},
|
||
|
||
// 获取值(类似 localStorage.getItem)
|
||
async get(key) {
|
||
const db = await this.init();
|
||
return new Promise((resolve) => {
|
||
const tx = db.transaction(this.storeName, 'readonly');
|
||
const request = tx.objectStore(this.storeName).get(key);
|
||
request.onsuccess = () => resolve(request.result);
|
||
});
|
||
},
|
||
|
||
// 删除值
|
||
async remove(key) {
|
||
const db = await this.init();
|
||
return new Promise((resolve) => {
|
||
const tx = db.transaction(this.storeName, 'readwrite');
|
||
tx.objectStore(this.storeName).delete(key);
|
||
tx.oncomplete = () => resolve();
|
||
});
|
||
},
|
||
|
||
// 清空所有
|
||
async clear() {
|
||
const db = await this.init();
|
||
return new Promise((resolve) => {
|
||
const tx = db.transaction(this.storeName, 'readwrite');
|
||
tx.objectStore(this.storeName).clear();
|
||
tx.oncomplete = () => resolve();
|
||
});
|
||
},
|
||
|
||
// 获取所有键
|
||
async keys() {
|
||
const db = await this.init();
|
||
return new Promise((resolve) => {
|
||
const tx = db.transaction(this.storeName, 'readonly');
|
||
const store = tx.objectStore(this.storeName);
|
||
const request = store.getAllKeys();
|
||
request.onsuccess = () => resolve(request.result);
|
||
});
|
||
}
|
||
};
|
||
export {KeyValueDB} |