File size: 2,518 Bytes
dbb54bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d66485
dbb54bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9d04c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
 * Minimal HTTP client for Quorum ``/api/v1`` — mirrors FastAPI error payloads.
 */

const baseURL = () =>
  import.meta.env.VITE_API_BASE_URL?.replace(/\/$/, "") || "/api/v1";

export class ApiError extends Error {
  constructor(
    message: string,
    readonly status: number,
    readonly body?: unknown,
  ) {
    super(message);
    this.name = "ApiError";
  }
}

export function parseDetail(payload: unknown): string {
  if (payload && typeof payload === "object" && "detail" in payload) {
    const d = (payload as { detail: unknown }).detail;
    if (typeof d === "string") return d;
    if (Array.isArray(d) && d[0] && typeof d[0] === "object" && "msg" in d[0]) {
      return String((d[0] as { msg: string }).msg);
    }
  }
  return "Request failed";
}

export async function apiFetch<T>(
  path: string,
  options: RequestInit & { skipAuth?: boolean } = {},
): Promise<T> {
  const { skipAuth, headers: hdr, ...rest } = options;
  const headers = new Headers(hdr);
  if (!headers.has("Content-Type") && rest.body && !(rest.body instanceof FormData)) {
    headers.set("Content-Type", "application/json");
  }

  if (!skipAuth) {
    const access = localStorage.getItem("quorum_access_token");
    if (access) headers.set("Authorization", `Bearer ${access}`);
  }

  const res = await fetch(`${baseURL()}${path.startsWith("/") ? path : `/${path}`}`, {
    ...rest,
    headers,
  });

  const text = await res.text();
  let json: unknown = undefined;
  if (text) {
    try {
      json = JSON.parse(text);
    } catch {
      json = text;
    }
  }

  if (!res.ok) {
    throw new ApiError(parseDetail(json), res.status, json);
  }

  return json as T;
}

/** Authenticated GET returning raw text (e.g. Prometheus exposition). */
export async function apiFetchText(
  path: string,
  options: RequestInit & { skipAuth?: boolean } = {},
): Promise<string> {
  const { skipAuth, headers: hdr, ...rest } = options;
  const headers = new Headers(hdr);
  if (!skipAuth) {
    const access = localStorage.getItem("quorum_access_token");
    if (access) headers.set("Authorization", `Bearer ${access}`);
  }
  const res = await fetch(`${baseURL()}${path.startsWith("/") ? path : `/${path}`}`, {
    ...rest,
    headers,
  });
  const text = await res.text();
  if (!res.ok) {
    let json: unknown = undefined;
    if (text) {
      try {
        json = JSON.parse(text);
      } catch {
        json = text;
      }
    }
    throw new ApiError(parseDetail(json), res.status, json);
  }
  return text;
}