Files
gym-bro/frontend/js/api.js
T

70 lines
1.7 KiB
JavaScript

// frontend/js/api.js
import { apiFetch } from "./auth.js";
async function jsonOrThrow(res, fallbackMessage) {
if (!res.ok) {
let detail = fallbackMessage;
try {
const err = await res.json();
if (typeof err.detail === "string") {
detail = err.detail;
} else if (Array.isArray(err.detail)) {
detail = err.detail
.map((d) => `${d.loc?.join(".") || ""}: ${d.msg || ""}`.trim())
.join("; ");
} else {
detail = JSON.stringify(err.detail || err);
}
} catch {
// ignore parse error
}
throw new Error(detail);
}
return await res.json();
}
export async function fetchBootstrapData() {
const res = await apiFetch("/bootstrap/");
return jsonOrThrow(res, "Failed to fetch bootstrap data");
}
export async function fetchWorkoutTypes() {
const res = await apiFetch("/workout-types/");
return jsonOrThrow(res, "Failed to fetch workout types");
}
export async function fetchMetricTypes() {
const res = await apiFetch("/metric-types/");
return jsonOrThrow(res, "Failed to fetch metric types");
}
export async function fetchClients() {
const res = await apiFetch("/clients/");
return jsonOrThrow(res, "Failed to fetch clients");
}
export async function fetchExerciseHistory(exerciseName, clientId = null) {
let path = `/exercises/history/${encodeURIComponent(exerciseName)}?limit=10`;
if (clientId) {
path += `&client_id=${clientId}`;
}
const res = await apiFetch(path);
return jsonOrThrow(res, "Failed to fetch history");
}
export async function syncData(payload) {
const res = await apiFetch("/sync/", {
method: "POST",
body: JSON.stringify(payload),
});
return jsonOrThrow(res, "Sync failed");
}