Update src/lib/api/product.ts

This commit is contained in:
2026-03-08 22:21:19 +00:00
parent 184c822595
commit d3dac0cee3

View File

@@ -1,68 +1,21 @@
interface ApiProduct {
export interface Product {
id: string;
name: string;
price: number;
description: string;
price: string;
imageSrc: string;
category: string;
imageAlt?: string;
description?: string;
}
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "https://api.example.com";
export const fetchProducts = async (): Promise<ApiProduct[]> => {
export async function fetchProducts(): Promise<Product[]> {
try {
const response = await fetch(`${API_BASE_URL}/products`);
const response = await fetch('/api/products');
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
throw new Error('Failed to fetch products');
}
return await response.json();
} catch (err) {
console.error("Failed to fetch products:", err);
return response.json();
} catch (error) {
console.error('Error fetching products:', error);
return [];
}
};
export const fetchProductById = async (id: string): Promise<ApiProduct | null> => {
try {
const response = await fetch(`${API_BASE_URL}/products/${id}`);
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
return await response.json();
} catch (err) {
console.error(`Failed to fetch product ${id}:`, err);
return null;
}
};
export const searchProducts = async (query: string): Promise<ApiProduct[]> => {
try {
const response = await fetch(
`${API_BASE_URL}/products/search?q=${encodeURIComponent(query)}`
);
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
return await response.json();
} catch (err) {
console.error("Failed to search products:", err);
return [];
}
};
export const fetchProductsByCategory = async (
category: string
): Promise<ApiProduct[]> => {
try {
const response = await fetch(
`${API_BASE_URL}/products/category/${category}`
);
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
return await response.json();
} catch (err) {
console.error(`Failed to fetch products in category ${category}:`, err);
return [];
}
};
}