webstore/ts/webstore.classes.webstore.ts
2023-10-02 19:10:30 +02:00

76 lines
1.8 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 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 && !globalThis.indexedDB) {
console.log('hey');
console.log(globalThis.indexedDB);
await smartenv.getSafeNodeModule('fake-indexeddb/auto');
if (!globalThis.indexedDB) {
const mod = await smartenv.getSafeNodeModule('fake-indexeddb');
globalThis.indexedDB = new mod.IDBFactory();
}
}
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);
}
}