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