This repository was archived by the owner on Nov 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBrowserDatabase.ts
More file actions
43 lines (40 loc) · 1.86 KB
/
BrowserDatabase.ts
File metadata and controls
43 lines (40 loc) · 1.86 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
namespace AdvancedServiceWorker {
export class BrowserDatabase {
private static databaseName: string = "advanced-service-worker";
private static storeName: string = "keyval";
private static getIdb(type: IDBTransactionMode, callback: { (store: IDBObjectStore): void; }): Promise<{}> {
return new Promise((resolve, reject) => {
const openreq = indexedDB.open(this.databaseName, 1);
openreq.onerror = () => reject(openreq.error);
openreq.onsuccess = () => resolve(openreq.result);
openreq.onupgradeneeded = () => {
openreq.result.createObjectStore(this.storeName);
};
}).then((db: IDBDatabase) => new Promise((resolve, reject) => {
const transaction = db.transaction(this.storeName, type);
transaction.oncomplete = () => resolve();
transaction.onabort = transaction.onerror = () => reject(transaction.error);
callback(transaction.objectStore(this.storeName));
}));
}
static saveOptions(options: Options): Promise<boolean> {
const scope = Condition.getRelativeUrl(options.scope);
return BrowserDatabase.getIdb("readwrite",
(store) => {
store.put(options, scope);
}).then(() => true,
(c) => {
console.log(c);
return false;
});
}
static loadOptions(scope: string): Promise<Options> {
scope = Condition.getRelativeUrl(scope);
let request: IDBRequest;
return BrowserDatabase.getIdb("readonly",
(store) => {
request = store.get(scope);
}).then(() => request.result as Options, () => null);
}
}
}