1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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!");
}
};