Add web worker initialization
This commit is contained in:
parent
f74fcabec7
commit
414f8e5dca
@ -25,35 +25,35 @@ export class Database {
|
||||
return Database.instance;
|
||||
}
|
||||
|
||||
// Initialize the database
|
||||
private async init(): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(this.dbName, this.dbVersion);
|
||||
// ============================================
|
||||
// INDEXEDDB WEB WORKER
|
||||
// ============================================
|
||||
|
||||
request.onupgradeneeded = () => {
|
||||
const db = request.result;
|
||||
private initIndexedDBWorker(): void {
|
||||
this.indexedDBWorker = new Worker(new URL('../workers/indexeddb.worker.js', import.meta.url), { type: 'module' });
|
||||
|
||||
this.indexedDBWorker.onmessage = (event) => {
|
||||
const { id, type, result, error } = event.data;
|
||||
const pending = this.pendingMessages.get(id);
|
||||
|
||||
if (pending) {
|
||||
this.pendingMessages.delete(id);
|
||||
|
||||
if (type === 'SUCCESS') {
|
||||
pending.resolve(result);
|
||||
} else if (type === 'ERROR') {
|
||||
pending.reject(new Error(error));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Object.values(this.storeDefinitions).forEach(({ name, options, indices }) => {
|
||||
if (!db.objectStoreNames.contains(name)) {
|
||||
let store = db.createObjectStore(name, options as IDBObjectStoreParameters);
|
||||
this.indexedDBWorker.onerror = (error) => {
|
||||
console.error('[Database] IndexedDB Worker error:', error);
|
||||
};
|
||||
}
|
||||
|
||||
indices.forEach(({ name, keyPath, options }) => {
|
||||
store.createIndex(name, keyPath, options);
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
request.onsuccess = async () => {
|
||||
this.db = request.result;
|
||||
resolve();
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
console.error('Database error:', request.error);
|
||||
reject(request.error);
|
||||
};
|
||||
});
|
||||
private async waitForWorkerReady(): Promise<void> {
|
||||
return this.sendMessageToWorker('INIT', {});
|
||||
}
|
||||
|
||||
public async getDb(): Promise<IDBDatabase> {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user