class IndexedDBManager {
constructor() {
this.dbName = 'GltfModelCache';
this.dbVersion = 1;
this.storeName = 'gltfModels';
}
// 打开或创建IndexedDB
openDB() {
return new Promise((resolve, reject) => {
const request = window.indexedDB.open(this.dbName, this.dbVersion);
request.onerror = (event) => {
console.error('Database error: ', event.target.errorCode);
reject(event.target.errorCode);
};
request.onsuccess = (event) => {
this.db = event.target.result;
resolve();
};
request.onupgradeneeded = (event) => {
const db = event.target.result;
if (!db.objectStoreNames.contains(this.storeName)) {
db.createObjectStore(this.storeName, { keyPath: 'url' });
}
};
});
}
// 将gltf模型存储到IndexedDB
saveGltfModel(url, arrayBuffer) {
return this.openDB().then(() => {
const transaction = this.db.transaction([this.storeName], 'readwrite');
const store = transaction.objectStore(this.storeName);
const request = store.put({ url, arrayBuffer });
return new Promise((resolve, reject) => {
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
});
});
}
// 从IndexedDB获取gltf模型
getGltfModel(url) {
return this.openDB().then(() => {
const transaction = this.db.transaction([this.storeName]);
const store = transaction.objectStore(this.storeName);
const request = store.get(url);
return new Promise((resolve, reject) => {
request.onsuccess = (event) => {
const gltfModel = event.target.result;
if (gltfModel) {
resolve(gltfModel.arrayBuffer);
} else {
reject('Model not found');
}
};
request.onerror = () => reject(request.error);
评论已关闭