webstore/ts/webstore.classes.webstore.ts

76 lines
1.8 KiB
TypeScript
Raw Normal View History

2022-05-28 10:33:10 +00:00
import * as plugins from './webstore.plugins.js';
2020-07-09 22:30:33 +00:00
2020-07-09 23:03:01 +00:00
export interface IWebStoreOptions {
2020-07-11 16:26:35 +00:00
dbName: string;
2020-07-09 23:03:01 +00:00
storeName: string;
}
2020-09-19 14:38:29 +00:00
export class WebStore<T = any> {
2020-07-09 23:03:01 +00:00
public db: plugins.idb.IDBPDatabase;
public options: IWebStoreOptions;
2020-09-19 14:58:06 +00:00
private initCalled: boolean = false;
private readyDeferred = plugins.smartpromise.defer();
2020-07-09 23:03:01 +00:00
constructor(optionsArg: IWebStoreOptions) {
this.options = optionsArg;
}
2020-09-18 10:12:02 +00:00
public async init() {
2020-09-19 14:58:06 +00:00
if (this.initCalled) {
2020-09-19 15:06:27 +00:00
await this.readyDeferred.promise;
return;
2020-09-19 14:58:06 +00:00
}
this.initCalled = true;
2022-05-28 10:33:10 +00:00
const smartenv = new plugins.smartenv.Smartenv();
2023-05-01 10:44:59 +00:00
if (!smartenv.isBrowser && !globalThis.indexedDB) {
console.log('hey');
console.log(globalThis.indexedDB);
2022-08-01 13:50:05 +00:00
await smartenv.getSafeNodeModule('fake-indexeddb/auto');
2023-05-01 10:44:59 +00:00
if (!globalThis.indexedDB) {
const mod = await smartenv.getSafeNodeModule('fake-indexeddb');
globalThis.indexedDB = new mod.IDBFactory();
}
2022-05-28 10:33:10 +00:00
}
2020-07-11 16:26:35 +00:00
this.db = await plugins.idb.openDB(this.options.dbName, 1, {
upgrade: (db) => {
db.createObjectStore(this.options.storeName);
2020-07-09 23:03:01 +00:00
},
});
2020-09-19 14:58:06 +00:00
this.readyDeferred.resolve();
2020-09-19 15:06:27 +00:00
return;
2020-07-09 23:03:01 +00:00
}
2020-09-19 14:02:15 +00:00
async get(key: string): Promise<T> {
2020-09-19 14:58:06 +00:00
await this.init();
2020-07-11 16:26:35 +00:00
return this.db.get(this.options.storeName, key);
2020-07-09 23:03:01 +00:00
}
2020-07-11 17:15:24 +00:00
async check(keyArg: string): Promise<boolean> {
2020-09-19 14:58:06 +00:00
await this.init();
2020-07-11 17:15:24 +00:00
const result = await this.get(keyArg);
return !!result;
}
async set(key: string, val: T) {
2020-09-19 15:06:27 +00:00
await this.init();
2020-07-11 16:26:35 +00:00
return this.db.put(this.options.storeName, val, key);
2020-07-09 23:03:01 +00:00
}
2020-07-11 17:15:24 +00:00
async delete(key: string) {
2020-09-19 14:58:06 +00:00
await this.init();
2020-07-11 16:26:35 +00:00
return this.db.delete(this.options.storeName, key);
2020-07-09 23:03:01 +00:00
}
async clear() {
2020-09-19 14:58:06 +00:00
await this.init();
2020-07-11 16:26:35 +00:00
return this.db.clear(this.options.storeName);
2020-07-09 23:03:01 +00:00
}
async keys() {
2020-09-19 14:58:06 +00:00
await this.init();
2020-07-11 16:26:35 +00:00
return this.db.getAllKeys(this.options.storeName);
2020-07-09 23:03:01 +00:00
}
2020-09-18 10:12:02 +00:00
}