Commit 84eafea4 by Sixong.Zhu

add

parent f6811858
Showing with 80 additions and 0 deletions
class DevAppTools {
private db!: IDBDatabase;
private readonly key = 'dev-tools';
private readonly valueKey = 'value';
private readonly table = 'dev-table';
private onReady() {
if (this.db) {
return Promise.resolve();
}
return new Promise<void>((resolve => {
if (indexedDB) {
const r = indexedDB.open(this.key, 1);
const setupDb = () => {
if (this.db && !this.db.objectStoreNames.contains(this.table)) {
this.db.createObjectStore(this.table, { keyPath: this.valueKey });
}
resolve();
};
r.onsuccess = (e) => {
this.db = (e.target as any).result;
setupDb();
};
r.onupgradeneeded = (e) => {
this.db = (e.target as any).result;
setupDb();
};
r.onerror = () => setupDb();
} else {
resolve();
}
}));
}
private buildTransaction(key: string) {
return this.db.transaction(key, "readwrite");
}
private buildStore(key: string) {
const transaction = this.buildTransaction(key);
return transaction.objectStore(key);
}
public isOpen() {
return new Promise<boolean>((resolve) => {
this.onReady().finally(() => {
if (!this.db) {
return resolve(false);
}
const store = this.buildStore(this.table);
const r = store.getKey(1);
r.onsuccess = (o) => resolve((o.target as any).result);
r.onerror = () => resolve(false);
});
});
}
public toggle() {
return new Promise<boolean>((resolve) => {
this.onReady().finally(() => {
this.isOpen().then(r => {
if (r) {
const store = this.buildStore(this.table);
const d = store.delete(1);
d.onsuccess = () => resolve(false);
d.onerror = () => resolve(false);
} else {
const store = this.buildStore(this.table);
const d = store.add({ value: 1 });
d.onsuccess = () => resolve(true);
d.onerror = () => resolve(true);
}
});
});
});
}
}
export const devAppTools = new DevAppTools();
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment