webstore/ts/webstore.classes.webstore.ts
2022-05-29 20:04:44 +02:00

71 lines
1.6 KiB
TypeScript

import * as plugins from './webstore.plugins.js';
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) {
await this.readyDeferred.promise;
return;
}
this.initCalled = true;
const smartenv = new plugins.smartenv.Smartenv();
if (!smartenv.isBrowser) {
await smartenv.getSafeNodeModule('fake-indexeddb/auto.js');
}
this.db = await plugins.idb.openDB(this.options.dbName, 1, {
upgrade: (db) => {
db.createObjectStore(this.options.storeName);
},
});
this.readyDeferred.resolve();
return;
}
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) {
await this.init();
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);
}
}