class Init extends HTMLElement {
#AppName = "customs-portal";
constructor() {
super();
}
async connectedCallback() {
await this.#CheckStorage();
const LocalVersion = await this.#GetValue(`${this.#AppName}_version`) || -1;
// Append local version to compare in endpoint, inject version to prevent browser caching this resource
const Response = await fetch(`customs-portal/package?v=${LocalVersion}c=27480066`);
if (Response.status == 200) {
const ResponseObj = await Response.json();
if (ResponseObj.version > LocalVersion) {
await this.#SetValue(`${this.#AppName}_version`, ResponseObj.version);
await this.#SetValue(`${this.#AppName}_data`, JSON.stringify(ResponseObj.data));
await this.#SetValue(`${this.#AppName}_info`, JSON.stringify(ResponseObj.info));
await this.#SetValue(`${this.#AppName}_changelog`, JSON.stringify(ResponseObj.changelog));
}
const Package = document.createElement("script");
Package.innerHTML = JSON.parse(await this.#GetValue(`${this.#AppName}_data`));
document.head.appendChild(Package);
new App();
}
}
#DB;
async #CheckStorage() {
await new Promise(async (resolve, reject) => {
const Req = window.indexedDB.open(`${this.#AppName}-db`, 5);
Req.onerror = () => {
reject("Could not open app database.");
};
Req.onsuccess = () => {
this.#DB = Req.result;
resolve();
};
Req.onupgradeneeded = (e) => {
this.#CheckSchema(e);
};
});
}
#CheckSchema(e) {
const DB = e.target.result;
if (!DB.objectStoreNames.contains("main")) {
DB.createObjectStore("main");
}
};
async #GetValue(Key) {
return await new Promise(async (resolve, reject) => {
const Request = this.#DB.transaction("main", "readwrite").objectStore("main").get(Key);
Request.onerror = () => {
reject();
};
Request.onsuccess = () => {
resolve(Request.result);
};
});
}
async #SetValue(Key, Value) {
await new Promise(async (resolve, reject) => {
const Request = this.#DB.transaction("main", "readwrite").objectStore("main").put(Value, Key);
Request.onerror = () => {
reject();
};
Request.onsuccess = () => {
resolve();
};
});
}
}
customElements.define("app-init", Init);