All files / src/lib/api categories.ts

0% Statements 0/64
100% Branches 0/0
0% Functions 0/1
0% Lines 0/64

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 58 59 60 61 62 63 64 65                                                                                                                                 
// API client functions for categories

export interface Category {
  id: number;
  title: string;
  slug: string;
  imageUrl?: string;
  description?: string;
  productCount?: number;
}

/**
 * Helper to extract data from API response
 */
function extractData<T>(result: { success?: boolean; data?: T } | T): T {
  if (result && typeof result === 'object' && 'data' in result) {
    return result.data as T;
  }
  return result as T;
}

/**
 * Fetch all categories
 */
export async function getCategories(includeProductCount = false): Promise<Category[]> {
  const params = new URLSearchParams();
  if (includeProductCount) params.append("includeProductCount", "true");

  const queryString = params.toString();
  const url = `/api/categories${queryString ? `?${queryString}` : ""}`;

  const response = await fetch(url);

  if (!response.ok) {
    throw new Error("Failed to fetch categories");
  }

  const result = await response.json();
  const data = extractData<Category[]>(result);
  return Array.isArray(data) ? data : [];
}

/**
 * Create a new category (admin only)
 */
export async function createCategory(categoryData: {
  title: string;
  slug?: string;
  imageUrl?: string;
  description?: string;
}): Promise<Category> {
  const response = await fetch("/api/categories", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"},
    body: JSON.stringify(categoryData)});

  if (!response.ok) {
    throw new Error("Failed to create category");
  }

  const result = await response.json();
  return extractData<Category>(result);
}