Skip to content

Instantly share code, notes, and snippets.

@pavanjoshi914
Created August 31, 2022 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pavanjoshi914/c16dd8ab7bec83b2322b8face795dc8e to your computer and use it in GitHub Desktop.
Save pavanjoshi914/c16dd8ab7bec83b2322b8face795dc8e to your computer and use it in GitHub Desktop.
import Dexie from "dexie";
import "fake-indexeddb/auto";
import browser from "webextension-polyfill";
import type { Allowance, Payment, Blocklist, Metadata } from "~/types";
class DB extends Dexie {
metadata: Dexie.Table<Metadata, number>
constructor() {
super("LBE");
this.version(x).stores({
metadata:
"++id,allowanceId,host,metadata,paymentHash,createdAt,type,contentUrl",
});
this.on("ready", this.loadFromStorage.bind(this));
this.metadata = this.table("metadata");
}
async saveToStorage() {
const metadataArray = await this.metadata.toArray();
await browser.storage.local.set({
allowances: allowanceArray,
payments: paymentsArray,
blocklist: blocklistArray,
metadata: metadataArray
});
return true;
}
// Loads the data from the browser.storage and adds the data to the IndexedDB.
// This is needed because the IndexedDB is not necessarily persistent,
// BUT maybe there are already entries in the IndexedDB (that depends on the browser).
// In that case we don't do anything as this would cause conflicts and errors.
// (this could use some DRY-up)
async loadFromStorage() {
console.info("Loading DB data from storage");
return browser.storage.local
.get(["allowances", "payments", "blocklist", "metadata"])
.then((result) => {
const metadataPromise = this.metadata.count().then((count) => {
// if the DB already has entries we do not need to add the data from the browser storage. We then already have the data in the indexeddb
if (count > 0) {
console.info(`Found ${count} metadata's already in the DB`);
return;
} else if (result.metadata && result.metadata.length > 0) {
// adding the data from the browser storage
return this.metadata
.bulkAdd(result.metadata)
.catch(Dexie.BulkError, function (e) {
console.error("Failed to add metadata; ignoring", e);
});
}
});
// wait for all allowances and payments to be loaded
return Promise.all([
metadataPromise
]);
})
.catch((e) => {
console.error("Failed to load DB data from storage", e);
});
}
}
const db = new DB();
export default db;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment