feat(offline): add IndexedDB mutation queue (enqueue, dequeue, mark synced/conflict)
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
// src/lib/offline/queue.ts
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { getOfflineDB, type QueuedAction } from "./db";
|
||||
|
||||
export interface EnqueueOptions {
|
||||
id?: string; // supply for idempotency
|
||||
}
|
||||
|
||||
export async function enqueueAction(
|
||||
actionName: string,
|
||||
payload: unknown,
|
||||
options: EnqueueOptions = {}
|
||||
): Promise<QueuedAction> {
|
||||
const db = await getOfflineDB();
|
||||
const id = options.id ?? uuidv4();
|
||||
const existing = await db.get("queue", id);
|
||||
if (existing) return existing;
|
||||
const action: QueuedAction = {
|
||||
id,
|
||||
actionName,
|
||||
payload,
|
||||
createdAt: Date.now(),
|
||||
attempts: 0,
|
||||
lastAttemptAt: null,
|
||||
status: "pending",
|
||||
};
|
||||
await db.put("queue", action);
|
||||
return action;
|
||||
}
|
||||
|
||||
export async function getQueuedActions(): Promise<QueuedAction[]> {
|
||||
const db = await getOfflineDB();
|
||||
const all = await db.getAllFromIndex("queue", "by-created");
|
||||
return all.filter((a) => a.status !== "synced");
|
||||
}
|
||||
|
||||
export async function dequeueAction(id: string): Promise<QueuedAction | null> {
|
||||
const db = await getOfflineDB();
|
||||
const tx = db.transaction("queue", "readwrite");
|
||||
const action = await tx.store.get(id);
|
||||
if (!action) {
|
||||
await tx.done;
|
||||
return null;
|
||||
}
|
||||
await tx.store.delete(id);
|
||||
await tx.done;
|
||||
return action;
|
||||
}
|
||||
|
||||
export async function markInFlight(id: string): Promise<void> {
|
||||
const db = await getOfflineDB();
|
||||
const action = await db.get("queue", id);
|
||||
if (!action) return;
|
||||
action.status = "in-flight";
|
||||
action.lastAttemptAt = Date.now();
|
||||
action.attempts += 1;
|
||||
await db.put("queue", action);
|
||||
}
|
||||
|
||||
export async function markSynced(id: string): Promise<void> {
|
||||
const db = await getOfflineDB();
|
||||
await db.delete("queue", id);
|
||||
}
|
||||
|
||||
export async function markConflict(id: string, error: string): Promise<void> {
|
||||
const db = await getOfflineDB();
|
||||
const action = await db.get("queue", id);
|
||||
if (!action) return;
|
||||
action.status = "conflict";
|
||||
action.error = error;
|
||||
await db.put("queue", action);
|
||||
}
|
||||
|
||||
export async function markFailed(id: string, error: string): Promise<void> {
|
||||
const db = await getOfflineDB();
|
||||
const action = await db.get("queue", id);
|
||||
if (!action) return;
|
||||
action.status = "failed";
|
||||
action.error = error;
|
||||
action.attempts += 1;
|
||||
action.lastAttemptAt = Date.now();
|
||||
await db.put("queue", action);
|
||||
}
|
||||
Reference in New Issue
Block a user