feat(stores): sync automatically
Some checks failed
TrafficCue CI / build (push) Has been cancelled
TrafficCue CI / build-android (push) Has been cancelled
TrafficCue CI / check (push) Has been cancelled

This commit is contained in:
2025-09-27 19:46:37 +02:00
parent b78f1aab06
commit 243d5c6437
3 changed files with 24 additions and 1 deletions

View File

@ -275,3 +275,8 @@ export async function postHazard(location: WorldLocation, type: string) {
}
return await res.json();
}
export async function ping() {
const res = await fetch(LNV_SERVER + "/ping").catch(() => ({ ok: false }));
return res.ok;
}

View File

@ -1,7 +1,7 @@
// import { getStores, putStore } from "./lnv";
import { openDB, type DBSchema } from "idb";
import { authFetch } from "./lnv";
import { authFetch, hasCapability, ping } from "./lnv";
import { LNV_SERVER } from "./hosts";
export interface Store {
@ -61,7 +61,20 @@ export const db = await openDB<TCDB>("tc", 1, {
const eventTarget = new EventTarget();
export async function trySync() {
const pingResult = await ping();
if(!pingResult) {
console.warn("[STORES] [trySync] LNV server is not reachable, skipping sync");
return { success: false, message: "LNV server is not reachable" };
}
await syncStores();
return { success: true };
}
export async function syncStores() {
if(!(await hasCapability("stores"))) {
return;
}
const changes = await Promise.all(await db.getAll("changes").then(changes => changes.map(async change => {
const storeData = await db.get("stores", change.id);
return { id: change.id, operation: change.operation, data: storeData?.data || null, modified_at: storeData?.modified_at || new Date().toISOString(), type: storeData?.type || "location", name: storeData?.name || "" };
@ -112,6 +125,7 @@ async function createStore(info: StoreInfo, data: object) {
await tx.objectStore("changes").add({ id, operation: "create" });
await tx.done;
eventTarget.dispatchEvent(new CustomEvent("store-updated", { detail: store }) );
await trySync();
return store;
}
@ -129,6 +143,7 @@ export async function updateStore(info: StoreInfo, data: object | null) {
await tx.objectStore("changes").add({ id: store.id, operation: "update" });
await tx.done;
eventTarget.dispatchEvent(new CustomEvent("store-updated", { detail: store }) );
await trySync();
return store;
}

View File

@ -1,6 +1,7 @@
import { mount } from "svelte";
import "./app.css";
import App from "./App.svelte";
import { trySync } from "$lib/services/stores.svelte";
if (location.href.includes("/oidc")) {
const url = new URL(location.href);
@ -22,4 +23,6 @@ const app = mount(App, {
target: document.getElementById("app")!,
});
await trySync();
export default app;