Files
photoanalyzer/frontend/js/api.js
domverse ce5c8db5bc US02-05: Build the Static Application Shell
Add the reusable browser shell primitives Phase B views build on:

- store.js: observable store (get/set/subscribe)
- events.js: job activity adapter — SSE preferred, polling fallback,
  sharing the event `seq` as cursor so a transport switch drops nothing
- api.js: cancellable() (AbortController) + job endpoints; aborted
  requests reject with code "cancelled"

Make the SSE stream generically consumable: emit default `message`
events with the type in the JSON payload instead of `event: <type>`, so
a browser EventSource receives the open-ended type set (state:*,
claimed, …) via onmessage without enumerating it. The `event: done`
sentinel and resumable `id:` cursors are unchanged.

Tests: frontend/js/tests/ in-browser unit suite (api errors +
cancellation, store transitions, routing, SSE→polling fallback) served
over the app's static mount and driven by tests/e2e/test_frontend_shell.py,
which also asserts asset loading, deep-link + reload restore, JSON-only
/api/v1, and a clean console/network. Reuses the installed playwright —
no JS toolchain added.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-06 15:47:52 +02:00

70 lines
2.7 KiB
JavaScript

// Single API client: one place for fetch, JSON, the error envelope, and request
// cancellation. Every method accepts an optional { signal } from cancellable().
export const BASE = "/api/v1";
async function request(path, { signal, ...options } = {}) {
let response;
try {
response = await fetch(BASE + path, {
headers: { "Content-Type": "application/json" },
signal,
...options,
});
} catch (error) {
// A caller-cancelled fetch is not a failure; tag it so views can ignore it.
if (error.name === "AbortError") {
error.code = "cancelled";
}
throw error;
}
let body = null;
try {
body = await response.json();
} catch (_) {
body = null;
}
if (!response.ok) {
const envelope = body && body.error ? body.error : {};
const error = new Error(envelope.message || response.statusText);
error.status = response.status;
error.code = envelope.code || "error";
throw error;
}
return body;
}
// Cancellation: hand callers a signal to pass into any request and a cancel() to
// abort the in-flight fetch. Aborted requests reject with code "cancelled".
export function cancellable() {
const controller = new AbortController();
return { signal: controller.signal, cancel: () => controller.abort() };
}
export const api = {
listAssets: (params = {}, opts = {}) =>
request("/inventory/assets?" + new URLSearchParams(params).toString(), opts),
listClusters: (params = {}, opts = {}) =>
request("/duplicates/clusters?" + new URLSearchParams(params).toString(), opts),
getCluster: (id, opts = {}) =>
request(`/duplicates/clusters/${encodeURIComponent(id)}`, opts),
decide: (id, payload, opts = {}) =>
request(`/duplicates/clusters/${encodeURIComponent(id)}/decision`, {
method: "POST",
body: JSON.stringify(payload),
...opts,
}),
thumbnailUrl: (assetId, size = 512) =>
`${BASE}/assets/${encodeURIComponent(assetId)}/thumbnail?size=${size}`,
// ── Jobs ────────────────────────────────────────────────────────────────
startJob: (payload, opts = {}) =>
request("/jobs", { method: "POST", body: JSON.stringify(payload), ...opts }),
getJob: (id, opts = {}) => request(`/jobs/${encodeURIComponent(id)}`, opts),
cancelJob: (id, opts = {}) =>
request(`/jobs/${encodeURIComponent(id)}/cancel`, { method: "POST", ...opts }),
jobEvents: (id, after = 0, opts = {}) =>
request(`/jobs/${encodeURIComponent(id)}/events?after=${after}`, opts),
jobEventsStreamUrl: (id, after = 0) =>
`${BASE}/jobs/${encodeURIComponent(id)}/events/stream?after=${after}`,
};