Files
craftvia/src/lib/offline/drafts.ts
T

43 lines
1.3 KiB
TypeScript

import { getOfflineStore } from "./db";
import { getOfflineState, whenReady } from "./outbox";
import { ctxKeyOf } from "./types";
/**
* Form drafts in IndexedDB (lane L7, Spec §22 "automatische Zwischenspeicherung"): note text,
* report draft … Stored per tenant+user context, deleted with the local data on logout.
* `key` is a stable form id, e.g. `note:<workOrderId>` or `report:<workOrderId>:daily`.
*/
const metaKey = (key: string) => `draft:${key}`;
export async function loadDraft<T>(key: string): Promise<T | null> {
if (!(await whenReady())) return null;
const ctx = getOfflineState().ctx;
if (!ctx) return null;
try {
return await (await getOfflineStore()).getMeta<T>(ctxKeyOf(ctx), metaKey(key));
} catch {
return null;
}
}
export async function saveDraft(key: string, value: unknown): Promise<void> {
const ctx = getOfflineState().ctx;
if (!ctx) return;
try {
await (await getOfflineStore()).setMeta(ctxKeyOf(ctx), metaKey(key), value);
} catch {
// quota / private mode — the form keeps working without a draft
}
}
export async function clearDraft(key: string): Promise<void> {
const ctx = getOfflineState().ctx;
if (!ctx) return;
try {
await (await getOfflineStore()).deleteMeta(ctxKeyOf(ctx), metaKey(key));
} catch {
/* ignore */
}
}