File size: 1,530 Bytes
20fb2bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4ad58f
 
 
 
 
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
const DEFAULT_TIMEOUT_MS = 25000;

export const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || "";

export async function fetchJson(path, options = {}) {
  const controller = new AbortController();
  const timeoutMs = options.timeoutMs || DEFAULT_TIMEOUT_MS;
  const timeout = window.setTimeout(() => controller.abort(), timeoutMs);

  try {
    const response = await fetch(`${apiBaseUrl}${path}`, {
      ...options,
      signal: controller.signal,
    });
    const text = await response.text();
    let data = null;
    if (text) {
      try {
        data = JSON.parse(text);
      } catch {
        throw new Error("The server returned an unreadable response. Please try again.");
      }
    }

    if (!response.ok) {
      throw new Error(
        data?.detail ||
          data?.errors?.join(" ") ||
          data?.error ||
          `Request failed with status ${response.status}.`
      );
    }

    return data;
  } catch (error) {
    if (error.name === "AbortError") {
      throw new Error("The request timed out. Check your connection and try again.");
    }
    if (error instanceof TypeError) {
      throw new Error("Could not reach the server. Check your connection and try again.");
    }
    throw error;
  } finally {
    window.clearTimeout(timeout);
  }
}

// Analyses of audio take minutes (long recordings much longer), so they get a longer timeout.
export function postForm(path, formData, timeoutMs = 30 * 60 * 1000) {
  return fetchJson(path, { method: "POST", body: formData, timeoutMs });
}