35 lines
1.0 KiB
TypeScript
35 lines
1.0 KiB
TypeScript
import { notFound } from "next/navigation";
|
||
|
||
import type { Catalog, Product } from "./types";
|
||
|
||
function apiBase(): string {
|
||
const url = process.env.API_INTERNAL_URL;
|
||
if (!url) {
|
||
throw new Error("API_INTERNAL_URL is not set");
|
||
}
|
||
return url.replace(/\/$/, "");
|
||
}
|
||
|
||
export async function getCatalog(categoryId?: string, sort = "price_asc"): Promise<Catalog> {
|
||
const params = new URLSearchParams({ sort });
|
||
if (categoryId) {
|
||
params.set("category_id", categoryId);
|
||
}
|
||
const response = await fetch(`${apiBase()}/products?${params}`, { cache: "no-store" });
|
||
if (!response.ok) {
|
||
throw new Error("Не удалось загрузить каталог");
|
||
}
|
||
return response.json();
|
||
}
|
||
|
||
export async function getProduct(id: string): Promise<Product> {
|
||
const response = await fetch(`${apiBase()}/products/${id}`, { cache: "no-store" });
|
||
if (response.status === 404) {
|
||
notFound();
|
||
}
|
||
if (!response.ok) {
|
||
throw new Error("Не удалось загрузить товар");
|
||
}
|
||
return response.json();
|
||
}
|