Files
aida_front/src/tool/indexedDB.js
2026-01-21 11:55:43 +08:00

71 lines
1.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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}