All files / src/lib/api wishlist.ts

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

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 66 67 68 69 70 71 72                                                                                                                                               
// API client functions for wishlist

export interface WishlistItem {
  id: number;
  title: string;
  price: number;
  discountedPrice: number;
  imgs?: {
    thumbnails: string[];
    previews: string[];
  };
}

/**
 * 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 user's wishlist items
 */
export async function getWishlist(): Promise<WishlistItem[]> {
  const response = await fetch("/api/wishlist");

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

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

/**
 * Add item to wishlist
 */
export async function addToWishlist(productId: number): Promise<WishlistItem> {
  const response = await fetch("/api/wishlist", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"},
    body: JSON.stringify({ productId })});

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error || "Failed to add to wishlist");
  }

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

/**
 * Remove item from wishlist
 */
export async function removeFromWishlist(productId: number): Promise<{ message: string }> {
  const response = await fetch(`/api/wishlist/${productId}`, {
    method: "DELETE"});

  if (!response.ok) {
    throw new Error("Failed to remove from wishlist");
  }

  const result = await response.json();
  return extractData<{ message: string }>(result);
}