Created
August 31, 2022 09:20
-
-
Save pavanjoshi914/c16dd8ab7bec83b2322b8face795dc8e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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