Files
meezi/web/dashboard/src/lib/offline/offline-db.ts
T

164 lines
5.0 KiB
TypeScript
Raw Normal View History

/**
* IndexedDB wrapper for the POS offline order queue.
* All reads/writes happen in a single "order_queue" object store.
*/
export type OfflineQueueItem = {
/** Local UUID primary key */
id: string;
/** "create_order" or "add_items_to_order" */
type: "create_order" | "add_items";
cafeId: string;
/**
* For add_items: the real server order ID.
* For create_order: null (no server ID yet).
*/
targetOrderId: string | null;
/** Raw body to POST/PUT */
payload: unknown;
createdAt: string;
retries: number;
status: "pending" | "failed";
};
const DB_NAME = "meezi_pos_offline";
const DB_VERSION = 2;
const STORE = "order_queue";
/** Generic key-value store (used to persist the React Query cache for offline reads). */
const KV_STORE = "kv";
let _db: IDBDatabase | null = null;
function openDb(): Promise<IDBDatabase> {
if (_db) return Promise.resolve(_db);
return new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, DB_VERSION);
req.onupgradeneeded = (e) => {
const db = (e.target as IDBOpenDBRequest).result;
if (!db.objectStoreNames.contains(STORE)) {
db.createObjectStore(STORE, { keyPath: "id" });
}
if (!db.objectStoreNames.contains(KV_STORE)) {
db.createObjectStore(KV_STORE);
}
};
req.onsuccess = () => {
_db = req.result;
resolve(_db);
};
req.onerror = () => reject(req.error);
});
}
export async function enqueueOfflineItem(
item: Omit<OfflineQueueItem, "retries" | "status">
): Promise<void> {
const db = await openDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE, "readwrite");
tx.objectStore(STORE).put({ ...item, retries: 0, status: "pending" });
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
export async function getQueueCount(): Promise<number> {
try {
const db = await openDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE, "readonly");
const req = tx.objectStore(STORE).count();
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
} catch {
return 0;
}
}
export async function getAllQueueItems(): Promise<OfflineQueueItem[]> {
try {
const db = await openDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE, "readonly");
const req = tx.objectStore(STORE).getAll();
req.onsuccess = () => resolve(req.result as OfflineQueueItem[]);
req.onerror = () => reject(req.error);
});
} catch {
return [];
}
}
export async function removeQueueItem(id: string): Promise<void> {
const db = await openDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE, "readwrite");
tx.objectStore(STORE).delete(id);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
export async function markQueueItemFailed(id: string): Promise<void> {
const db = await openDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE, "readwrite");
const store = tx.objectStore(STORE);
const getReq = store.get(id);
getReq.onsuccess = () => {
const item = getReq.result as OfflineQueueItem;
if (item) store.put({ ...item, status: "failed", retries: item.retries + 1 });
};
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
// ─── Generic key-value store (React Query cache persistence) ───────────────────
/** Store an arbitrary JSON-serializable value under a key. Never throws. */
export async function kvSet(key: string, value: unknown): Promise<void> {
try {
const db = await openDb();
await new Promise<void>((resolve, reject) => {
const tx = db.transaction(KV_STORE, "readwrite");
tx.objectStore(KV_STORE).put(value, key);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
} catch {
// IndexedDB unavailable / quota exceeded / blocked — degrade silently.
}
}
/** Read a value previously stored with {@link kvSet}. Returns undefined on any failure. */
export async function kvGet<T>(key: string): Promise<T | undefined> {
try {
const db = await openDb();
return await new Promise<T | undefined>((resolve, reject) => {
const tx = db.transaction(KV_STORE, "readonly");
const req = tx.objectStore(KV_STORE).get(key);
req.onsuccess = () => resolve(req.result as T | undefined);
req.onerror = () => reject(req.error);
});
} catch {
return undefined;
}
}
/** Remove a persisted value (e.g. on logout, to avoid leaking another user's cache). */
export async function kvDelete(key: string): Promise<void> {
try {
const db = await openDb();
await new Promise<void>((resolve, reject) => {
const tx = db.transaction(KV_STORE, "readwrite");
tx.objectStore(KV_STORE).delete(key);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
} catch {
// ignore
}
}