57 lines
1.5 KiB
JavaScript
57 lines
1.5 KiB
JavaScript
export class AssetStore {
|
|
static #isInternalConstructing = false;
|
|
static #idb = globalThis.indexedDB;
|
|
|
|
constructor(db) {
|
|
if (!AssetStore.#isInternalConstructing) {
|
|
throw new TypeError("Gesundheit is not constructable - use Gesundheit.load()");
|
|
}
|
|
AssetStore.#isInternalConstructing = false;
|
|
|
|
this.db = db;
|
|
}
|
|
|
|
async add(name, mime, bytes) {
|
|
const transaction = this.db.transaction(["asset"], "readwrite");
|
|
|
|
return await new Promise((resolve, reject) => {
|
|
transaction.oncomplete = () => {
|
|
resolve();
|
|
};
|
|
|
|
transaction.onerror = () => {
|
|
reject();
|
|
};
|
|
|
|
const objectStore = transaction.objectStore("asset");
|
|
|
|
objectStore.add({ name, mime, bytes });
|
|
});
|
|
}
|
|
|
|
static async load(name) {
|
|
/* remove when not developing db */
|
|
this.#idb.deleteDatabase(name);
|
|
const req = this.#idb.open(name);
|
|
const db = await new Promise((resolve, reject) => {
|
|
req.onerror = () => {
|
|
reject(req.error);
|
|
};
|
|
|
|
req.onupgradeneeded = () => {
|
|
const db = req.result;
|
|
|
|
db.createObjectStore("asset", {
|
|
keyPath: "name",
|
|
});
|
|
};
|
|
|
|
req.onsuccess = () => {
|
|
resolve(req.result);
|
|
};
|
|
});
|
|
this.#isInternalConstructing = true;
|
|
return new AssetStore(db);
|
|
}
|
|
}
|