Platform backbone (plan 2026-10-13-plattform-rueckgrat), all tasks reviewed: - webhooks with delivery table, retries and stable delivery id - calendar handlers; a finished task removes its Outlook event - tasks, automations, inspections, varroa, treatments, feedings, harvests, colonies, wintering, stock and bottling record domain events in the same transaction; legacy post-commit calls removed - row locks through one helper (lockRowForUpdate, lockRowsForShare, lockRowsForUpdate) - job framework with JobRun, cli exit codes, cleanup, task templates, daily evaluation, hourly app-backup and the rekey job - system API and page "Verwaltung > System" with retry - @nestjs/schedule removed, guard tests against in-process schedulers Field capture T3 (plan 2026-10-13-t3-erfassung-am-stand), all tasks reviewed: - inspection photo offline without metadata - bulk capture for treatments, feedings and varroa (backend + frontend) - offline stand mode with service worker, offline pages and packs - offline session, cold start and logout on shared devices Docs: ARCHITECTURE.md assumptions and sections updated, TASKS.md. Gates: backend lint, typecheck, 1770 unit, 420 e2e, build, no schema drift; frontend lint, typecheck, 913 tests, build. Not rolled out. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
169 lines
6.1 KiB
TypeScript
169 lines
6.1 KiB
TypeScript
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { getConnectivity, reportRequestOutcome } from "@/lib/offline/connectivity";
|
|
import {
|
|
DEFAULT_TIMEOUT_MS,
|
|
DOWNLOAD_TIMEOUT_MS,
|
|
NON_IDEMPOTENT_WRITE_TIMEOUT_MS,
|
|
UPLOAD_TIMEOUT_MS,
|
|
} from "@/lib/http/fetch-with-timeout";
|
|
import { expectTimeoutAt, stubHangingFetch } from "@/lib/http/deadline-test-helper";
|
|
import { getAccessToken, setAccessToken, setRefreshedTokenHandler } from "./token-store";
|
|
import { ApiError, apiFetch, apiFetchBlob, apiFetchFormData } from "./api-client";
|
|
|
|
vi.mock("../config/runtime-config", () => ({
|
|
getApiUrl: vi.fn().mockResolvedValue("http://api.test"),
|
|
}));
|
|
|
|
function jsonResponse(status: number, body: unknown): Response {
|
|
return new Response(JSON.stringify(body), {
|
|
status,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
}
|
|
|
|
describe("api-client", () => {
|
|
beforeEach(() => {
|
|
setAccessToken(null);
|
|
reportRequestOutcome("reached-server");
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals();
|
|
});
|
|
|
|
it("ApiError carries the parsed JSON body", async () => {
|
|
vi.stubGlobal(
|
|
"fetch",
|
|
vi.fn().mockResolvedValue(jsonResponse(400, { message: "Ungültig", invalidColonyIds: ["c1"] })),
|
|
);
|
|
const error = await apiFetch("/x").catch((e: unknown) => e);
|
|
expect(error).toBeInstanceOf(ApiError);
|
|
const apiError = error as ApiError;
|
|
expect(apiError.status).toBe(400);
|
|
expect(apiError.message).toBe("Ungültig");
|
|
expect((apiError.body as { invalidColonyIds: string[] }).invalidColonyIds).toEqual(["c1"]);
|
|
});
|
|
|
|
it("reports network-error on a failed fetch and reached-server on any HTTP answer", async () => {
|
|
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new TypeError("Failed to fetch")));
|
|
await expect(apiFetch("/x")).rejects.toBeInstanceOf(TypeError);
|
|
expect(getConnectivity()).toBe("offline");
|
|
|
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse(500, { message: "boom" })));
|
|
await expect(apiFetch("/x")).rejects.toBeInstanceOf(ApiError);
|
|
expect(getConnectivity()).toBe("online");
|
|
});
|
|
|
|
describe("timeouts", () => {
|
|
beforeEach(() => {
|
|
vi.useFakeTimers();
|
|
stubHangingFetch();
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
it("apiFetch: GET and keyed writes 4 s, unkeyed writes 15 s", async () => {
|
|
await expectTimeoutAt(() => apiFetch("/x"), DEFAULT_TIMEOUT_MS);
|
|
await expectTimeoutAt(
|
|
() => apiFetch("/x", { method: "POST", headers: { "Idempotency-Key": "k" } }),
|
|
DEFAULT_TIMEOUT_MS,
|
|
);
|
|
await expectTimeoutAt(() => apiFetch("/x", { method: "POST" }), NON_IDEMPOTENT_WRITE_TIMEOUT_MS);
|
|
});
|
|
|
|
it("apiFetchFormData uses 30 s by default and honours timeoutMs", async () => {
|
|
await expectTimeoutAt(() => apiFetchFormData("/x", new FormData()), UPLOAD_TIMEOUT_MS);
|
|
await expectTimeoutAt(
|
|
() => apiFetchFormData("/x", new FormData(), { timeoutMs: 5_000 }),
|
|
5_000,
|
|
);
|
|
});
|
|
|
|
it("apiFetchFormData passes options.headers through", async () => {
|
|
const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200, {}));
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
await apiFetchFormData("/x", new FormData(), { headers: { "Idempotency-Key": "k9" } });
|
|
const init = fetchMock.mock.calls[0][1] as RequestInit;
|
|
expect(new Headers(init.headers).get("Idempotency-Key")).toBe("k9");
|
|
});
|
|
|
|
it("apiFetchBlob uses 60 s", async () => {
|
|
await expectTimeoutAt(() => apiFetchBlob("/x", "f.csv"), DOWNLOAD_TIMEOUT_MS);
|
|
});
|
|
});
|
|
|
|
it("apiFetchBlob builds an ApiError with the parsed body", async () => {
|
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse(403, { message: "Nein", why: 1 })));
|
|
const error = (await apiFetchBlob("/x", "f.csv").catch((e: unknown) => e)) as ApiError;
|
|
expect(error).toBeInstanceOf(ApiError);
|
|
expect(error.status).toBe(403);
|
|
expect(error.body).toEqual({ message: "Nein", why: 1 });
|
|
});
|
|
});
|
|
|
|
describe("api-client token refresh", () => {
|
|
beforeEach(() => {
|
|
setAccessToken(null);
|
|
reportRequestOutcome("reached-server");
|
|
});
|
|
|
|
afterEach(() => {
|
|
setRefreshedTokenHandler(null);
|
|
vi.unstubAllGlobals();
|
|
});
|
|
|
|
function stubServer(refreshBody: unknown) {
|
|
const fetchMock = vi.fn(async (url: string) => {
|
|
if (url.endsWith("/auth/refresh")) return jsonResponse(200, refreshBody);
|
|
const retried = fetchMock.mock.calls.filter(([called]) => called === url).length > 1;
|
|
return retried ? jsonResponse(200, { ok: true }) : jsonResponse(401, {});
|
|
});
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
return fetchMock;
|
|
}
|
|
|
|
it("retries with the new token once the handler accepts it", async () => {
|
|
const handler = vi.fn().mockResolvedValue(true);
|
|
setRefreshedTokenHandler(handler);
|
|
stubServer({ accessToken: "fresh" });
|
|
|
|
await expect(apiFetch("/things")).resolves.toEqual({ ok: true });
|
|
|
|
expect(handler).toHaveBeenCalledWith("fresh");
|
|
});
|
|
|
|
it("does not retry - and keeps no token - when the handler rejects it (another account)", async () => {
|
|
setRefreshedTokenHandler(vi.fn().mockResolvedValue(false));
|
|
const fetchMock = stubServer({ accessToken: "other-users-token" });
|
|
|
|
await expect(apiFetch("/things")).rejects.toMatchObject({ status: 401 });
|
|
|
|
expect(getAccessToken()).toBeNull();
|
|
expect(fetchMock.mock.calls.filter(([url]) => String(url).endsWith("/things"))).toHaveLength(1);
|
|
});
|
|
|
|
it("takes the token as it is without a handler", async () => {
|
|
stubServer({ accessToken: "fresh" });
|
|
|
|
await expect(apiFetch("/things")).resolves.toEqual({ ok: true });
|
|
|
|
expect(getAccessToken()).toBe("fresh");
|
|
});
|
|
|
|
it.each([
|
|
["blobs", () => apiFetchBlob("/export", "x.csv")],
|
|
["form data", () => apiFetchFormData("/upload", new FormData())],
|
|
])("also asks the handler before retrying %s", async (_name, call) => {
|
|
const handler = vi.fn().mockResolvedValue(false);
|
|
setRefreshedTokenHandler(handler);
|
|
stubServer({ accessToken: "other" });
|
|
|
|
await expect(call()).rejects.toBeInstanceOf(ApiError);
|
|
|
|
expect(handler).toHaveBeenCalledWith("other");
|
|
expect(getAccessToken()).toBeNull();
|
|
});
|
|
});
|