/** * REST client for /api: prefixes the path, resolves to the body, and turns * failures into an ApiError carrying the backend's `error` message. Not for * the NDJSON streams or the radio probe. */ import axios from "axios"; export class ApiError extends Error { /** `status` is undefined when no response arrived at all. */ constructor(message, status, data) { super(message); this.name = "ApiError"; this.status = status; this.data = data; } } /** * @param {string} path below /api, with its leading slash * @param {object} [options] `body` (JSON or FormData), `fallback` message * when the backend sent none; anything else goes to axios. */ async function request(method, path, { body, fallback, ...config } = {}) { try { const res = await axios.request({ method, url: `/api${path}`, data: body, ...config, }); return res.data; } catch (err) { 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 }), };