All files / src/lib api-client.ts

100% Statements 17/17
90% Branches 9/10
100% Functions 4/4
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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      22x 22x               21x 6x 6x 6x 5x       6x       15x 1x     14x   7x 6x   1x         5x           15x             2x          
import { ApiError } from "./api-error";
 
async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
  try {
    const response = await fetch(path, {
      headers: {
        "Content-Type": "application/json",
        ...init?.headers,
      },
      ...init,
    });
 
    if (!response.ok) {
      let errorMessage = `HTTP ${response.status}`;
      try {
        const error = await response.json();
        errorMessage = error.error || errorMessage;
      } catch {
        // If response is not JSON, use status message
      }
      throw new ApiError(response.status, errorMessage);
    }
 
    // Handle 204 No Content
    if (response.status === 204) {
      return undefined as T;
    }
 
    return response.json();
  } catch (error) {
    if (error instanceof ApiError) {
      throw error;
    }
    throw new ApiError(500, error instanceof Error ? error.message : "Unknown error");
  }
}
 
export async function apiGet<T>(path: string): Promise<T> {
  return apiFetch<T>(path, {
    method: "GET",
  });
}
 
export async function apiPost<T>(path: string, body: unknown): Promise<T> {
  return apiFetch<T>(path, {
    method: "POST",
    body: JSON.stringify(body),
  });
}
 
export async function apiPatch<T>(path: string, body: unknown): Promise<T> {
  return apiFetch<T>(path, {
    method: "PATCH",
    body: JSON.stringify(body),
  });
}