/** * The REST half of the API client, beside graphql.js: a thin axios wrapper for * the tracker's JSON endpoints under /jobs/api that are not GraphQL (the * capture token and the email sync controls on the Settings page). * * It does two things a bare axios call does not: * - prefixes the API base, so callers name the route * (`api.get("/admin/capture-token")`); * - turns a failure into an ApiError whose `message` is the server's * `{"error": "..."}` body when there is one. * * Resolves to the parsed response body, not the axios response. A 401 means * the main site's session has lapsed, and sends the browser to its login. */ import axios from "axios"; import { goToLogin } from "@/session"; export class ApiError extends Error { /** * @param {string} message * @param {number|undefined} status HTTP status; undefined when no response * arrived at all (network down, backend restarting) * @param {*} data the parsed error body, if any */ constructor(message, status, data) { super(message); this.name = "ApiError"; this.status = status; this.data = data; } } /** * @param {string} method * @param {string} path route below the API base, with its leading slash * @param {object} [options] * @param {*} [options.body] JSON-serialisable body, or a FormData for * multipart uploads (axios sets the boundary itself) * @param {string} [options.fallback] message to use when the backend sent no * `error` string — callers pass the sentence their UI shows * Any other option (`headers`, `params`, `onUploadProgress`, `signal`, …) is * handed to axios unchanged. */ async function request(method, path, { body, fallback, ...config } = {}) { try { const res = await axios.request({ method, url: `${import.meta.env.BASE_URL}api${path}`, data: body, ...config, }); return res.data; } catch (err) { if (err.response?.status === 401) goToLogin(); const data = err.response?.data; const serverMessage = typeof data?.error === "string" ? data.error : ""; throw new ApiError( serverMessage || fallback || err.message, err.response?.status, data, ); } } export const api = { get: (path, options) => request("get", path, options), delete: (path, options) => request("delete", path, options), post: (path, body, options) => request("post", path, { ...options, body }), put: (path, body, options) => request("put", path, { ...options, body }), patch: (path, body, options) => request("patch", path, { ...options, body }), };