webstore/ts/webstore.classes.webstore.ts
2020-09-19 14:58:06 +00:00

62 lines
1.4 KiB
TypeScript

import * as plugins from './webstore.plugins';
export interface IWebStoreOptions {
dbName: string;
storeName: string;
}
export class WebStore<T = any> {
public db: plugins.idb.IDBPDatabase;
public objectStore: plugins.idb.IDBPObjectStore;
public options: IWebStoreOptions;
private initCalled: boolean = false;
private readyDeferred = plugins.smartpromise.defer();
constructor(optionsArg: IWebStoreOptions) {
this.options = optionsArg;
}
public async init() {
if (this.initCalled) {
return this.readyDeferred.promise;
}
this.initCalled = true;
this.db = await plugins.idb.openDB(this.options.dbName, 1, {
upgrade: (db) => {
db.createObjectStore(this.options.storeName);
},
});
this.readyDeferred.resolve();
}
async get(key: string): Promise<T> {
await this.init();
return this.db.get(this.options.storeName, key);
}
async check(keyArg: string): Promise<boolean> {
await this.init();
const result = await this.get(keyArg);
return !!result;
}
async set(key: string, val: T) {
return this.db.put(this.options.storeName, val, key);
}
async delete(key: string) {
await this.init();
return this.db.delete(this.options.storeName, key);
}
async clear() {
await this.init();
return this.db.clear(this.options.storeName);
}
async keys() {
await this.init();
return this.db.getAllKeys(this.options.storeName);
}
}