invix_test_task/web/lib/api.ts

35 lines
1.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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();
}