import { openDB, deleteDB } from 'idb'; export let db; const dbName = !isDevServer ? 'oeffisearch' : 'oeffisearch_dev'; class DataStorage { constructor(idb) { this.idb = idb; } static async open() { const idb = await openDB(dbName, 1, { upgrade: async (db, oldVersion, newVersion, transaction) => { console.log(`upgrading database from ${oldVersion} to ${newVersion}`); switch (oldVersion) { case 0: db.createObjectStore('journey', { keyPath: 'refreshToken' }); db.createObjectStore('journeysOverview', { keyPath: 'slug' }); db.createObjectStore('journeysHistory', { autoIncrement: true }); } } }); return new DataStorage(idb); } async addJourneys(journeyEntries, overviewEntry, historyEntry) { const tx = this.idb.transaction(['journey', 'journeysOverview', 'journeysHistory'], 'readwrite'); const journeyStore = tx.objectStore('journey'); const journeysOverviewStore = tx.objectStore('journeysOverview'); const journeysHistoryStore = tx.objectStore('journeysHistory'); let proms = journeyEntries.map(j => journeyStore.put(j)); if (overviewEntry.historyEntryId === undefined) overviewEntry.historyEntryId = await journeysHistoryStore.put(historyEntry); proms.push(journeysOverviewStore.put(overviewEntry)); proms.push(tx.done); await Promise.all(proms); } async getHistory(profile) { const tx = this.idb.transaction('journeysHistory'); const history = []; for await (const cursor of tx.store) { if (profile !== undefined && profile !== cursor.value.profile) continue; history.push({ ...cursor.value, key: cursor.key, }); } return history; } async addHistoryEntry(entry) { return await this.idb.put('journeysHistory', entry); } async updateHistoryEntry(id, entry) { return await this.idb.put('journeysHistory', entry, id); } async getHistoryEntry(id) { return await this.idb.get('journeysHistory', id); } async getJourneysOverview(slug) { return await this.idb.get('journeysOverview', slug); } async getJourney(refreshToken) { return await this.idb.get('journey', refreshToken); } async updateJourney(data) { return await this.idb.put('journey', data); } } export const clearDataStorage = async () => await deleteDB(dbName); export const initDataStorage = async () => { try { db = await DataStorage.open(); } catch(e) { console.log("IndexedDB initialization failed: ", e); alert("IndexedDB initialization failed!"); } };