feat: offline-fähige PWA mit IndexedDB-Sync für Durchsichten

Service Worker (public/sw.js) cached die App-Shell für Seiten-GETs
(network-first, cache-fallback). Durchsichten, die offline gespeichert
werden, landen in einer IndexedDB-Warteschlange (idb) statt zu
scheitern und werden automatisch synchronisiert, sobald wieder
Netzwerk verfügbar ist (Mount + online-Event), mit manuellem Retry
über ein Badge im App-Header. Ein modulweiter In-Flight-Lock in
sync.ts verhindert doppelte Synchronisierung bei gleichzeitigen
Aufrufen (gefunden über React-StrictMode-Doppel-Mount, das ohne den
Lock dieselbe Durchsicht zweimal anlegte).
This commit is contained in:
Nick Szaunig committed 2026-08-25 01:14:18 +02:00
1 parent 20239885b4
commit eb66c4bd53
11 files changed
+319 -2

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
import { openDB, DBSchema, IDBPDatabase } from "idb";
import { CreateInspectionInput } from "@/lib/inspections/types";
interface OfflineDB extends DBSchema {
"pending-inspections": {
key: number;
value: PendingInspection;
};
}
export interface PendingInspection {
id: number;
input: CreateInspectionInput;
queuedAt: string;
}
const DB_NAME = "apicore-offline";
const DB_VERSION = 1;
const STORE_NAME = "pending-inspections";
let dbPromise: Promise<IDBPDatabase<OfflineDB>> | null = null;
function getDb(): Promise<IDBPDatabase<OfflineDB>> {
if (!dbPromise) {
dbPromise = openDB<OfflineDB>(DB_NAME, DB_VERSION, {
upgrade(db) {
db.createObjectStore(STORE_NAME, { keyPath: "id", autoIncrement: true });
},
});
}
return dbPromise;
}
export async function queueInspection(input: CreateInspectionInput): Promise<void> {
const db = await getDb();
await db.add(STORE_NAME, { input, queuedAt: new Date().toISOString() } as PendingInspection);
}
export async function getPendingInspections(): Promise<PendingInspection[]> {
const db = await getDb();
return db.getAll(STORE_NAME);
}
export async function removePendingInspection(id: number): Promise<void> {
const db = await getDb();
await db.delete(STORE_NAME, id);
}
export async function countPendingInspections(): Promise<number> {
const db = await getDb();
return db.count(STORE_NAME);
}
@@ -0,0 +1,78 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
import { ApiError } from "@/lib/auth/api-client";
import { createInspection } from "@/lib/inspections/api";
import { getPendingInspections, removePendingInspection } from "./db";
import { syncPendingInspections } from "./sync";
vi.mock("@/lib/inspections/api", () => ({
createInspection: vi.fn(),
}));
vi.mock("./db", () => ({
getPendingInspections: vi.fn(),
removePendingInspection: vi.fn(),
}));
const mockedCreateInspection = vi.mocked(createInspection);
const mockedGetPending = vi.mocked(getPendingInspections);
const mockedRemovePending = vi.mocked(removePendingInspection);
function pendingEntry(id: number) {
return {
id,
input: { colonyId: `colony-${id}`, date: "2026-01-01T00:00:00.000Z" },
queuedAt: "2026-01-01T00:00:00.000Z",
};
}
describe("syncPendingInspections", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("syncs every queued entry and removes it from the queue", async () => {
mockedGetPending.mockResolvedValue([pendingEntry(1), pendingEntry(2)]);
mockedCreateInspection.mockResolvedValue({ id: "x" } as never);
const result = await syncPendingInspections();
expect(result).toEqual({ synced: 2, failed: 0 });
expect(mockedRemovePending).toHaveBeenCalledWith(1);
expect(mockedRemovePending).toHaveBeenCalledWith(2);
});
it("keeps a rejected entry queued and continues with the rest on a server-side ApiError", async () => {
mockedGetPending.mockResolvedValue([pendingEntry(1), pendingEntry(2)]);
mockedCreateInspection
.mockRejectedValueOnce(new ApiError(400, "invalid colony"))
.mockResolvedValueOnce({ id: "x" } as never);
const result = await syncPendingInspections();
expect(result).toEqual({ synced: 1, failed: 1 });
expect(mockedRemovePending).not.toHaveBeenCalledWith(1);
expect(mockedRemovePending).toHaveBeenCalledWith(2);
});
it("stops immediately on a network failure, leaving the rest queued", async () => {
mockedGetPending.mockResolvedValue([pendingEntry(1), pendingEntry(2)]);
mockedCreateInspection.mockRejectedValueOnce(new TypeError("Failed to fetch"));
const result = await syncPendingInspections();
expect(result).toEqual({ synced: 0, failed: 1 });
expect(mockedCreateInspection).toHaveBeenCalledTimes(1);
expect(mockedRemovePending).not.toHaveBeenCalled();
});
it("shares a single in-flight run across concurrent callers instead of double-processing the queue", async () => {
mockedGetPending.mockResolvedValue([pendingEntry(1)]);
mockedCreateInspection.mockResolvedValue({ id: "x" } as never);
const [first, second] = await Promise.all([syncPendingInspections(), syncPendingInspections()]);
expect(first).toBe(second);
expect(mockedGetPending).toHaveBeenCalledTimes(1);
expect(mockedCreateInspection).toHaveBeenCalledTimes(1);
});
});
+40
View File
@@ -0,0 +1,40 @@
import { ApiError } from "@/lib/auth/api-client";
import { createInspection } from "@/lib/inspections/api";
import { getPendingInspections, removePendingInspection } from "./db";
export interface SyncResult {
synced: number;
failed: number;
}
let inFlightSync: Promise<SyncResult> | null = null;
export function syncPendingInspections(): Promise<SyncResult> {
if (!inFlightSync) {
inFlightSync = runSync().finally(() => {
inFlightSync = null;
});
}
return inFlightSync;
}
async function runSync(): Promise<SyncResult> {
const pending = await getPendingInspections();
let synced = 0;
let failed = 0;
for (const entry of pending) {
try {
await createInspection(entry.input);
await removePendingInspection(entry.id);
synced += 1;
} catch (error) {
failed += 1;
if (!(error instanceof ApiError)) {
break;
}
}
}
return { synced, failed };
}