-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompromiseIndexedDb.ts
More file actions
74 lines (57 loc) · 1.9 KB
/
compromiseIndexedDb.ts
File metadata and controls
74 lines (57 loc) · 1.9 KB
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
"use client";
export default class CompromiseIndexedDb implements ICompromiseStorage {
storedDb: IDBDatabase | undefined = undefined;
getDatabaseInstance(): Promise<IDBDatabase> {
if (this.storedDb !== undefined) return Promise.resolve(this.storedDb);
const request = indexedDB.open("tripsecretary");
request.onupgradeneeded = function () {
const localDb = request.result;
const store = localDb.createObjectStore("compromise", { keyPath: "id" });
store.createIndex("by_date", "date");
};
return new Promise((resolve, reject) => {
request.onsuccess = () => {
this.storedDb = request.result;
resolve(request.result);
};
request.onerror = (e) => {
console.error("Failed to start the indexed db");
reject(e);
};
});
}
async getCompromisesForTheDate(date: string): Promise<any> {
const db = await this.getDatabaseInstance();
const tx = db.transaction("compromise", "readonly");
const store = tx.objectStore("compromise");
const index = store.index("by_date");
const getRequest = index.getAll(date);
return new Promise((resolve) => {
getRequest.onsuccess = () => {
resolve(getRequest.result);
};
});
}
async upsertCompromise(obj: any): Promise<void> {
const db = await this.getDatabaseInstance();
const tx = db.transaction("compromise", "readwrite");
const store = tx.objectStore("compromise");
store.put(obj);
return new Promise((resolve) => {
tx.oncomplete = () => {
resolve();
};
});
}
async deleteCompromise(id: string): Promise<void> {
const db = await this.getDatabaseInstance();
const tx = db.transaction("compromise", "readwrite");
const store = tx.objectStore("compromise");
store.delete(id);
return new Promise((resolve) => {
tx.oncomplete = () => {
resolve();
};
});
}
}