add client rest api

This commit is contained in:
Profile Profile
2026-02-15 23:05:45 +03:00
parent 131deebffc
commit abcc214ef6
4 changed files with 309 additions and 269 deletions

View File

@@ -0,0 +1,45 @@
// src/lib/api/wp-rest-get-client.ts
function joinUrl(base: string, path: string) {
return `${base.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
}
export async function fetchWPRestGet<T = any>(
path: string,
query: Record<string, any> = {}
): Promise<T> {
const baseUrl = import.meta.env.WP_REST_BASE_URL; // например: https://site.ru
if (!baseUrl) {
throw new Error("WP_REST_BASE_URL is not defined in environment variables");
}
const endpoint = joinUrl(baseUrl, "/wp-json/");
const url = new URL(joinUrl(endpoint, path));
console.log(url);
const params = new URLSearchParams();
for (const [k, v] of Object.entries(query)) {
if (v === undefined || v === null) continue;
if (Array.isArray(v)) v.forEach((x) => params.append(k, String(x)));
else params.set(k, String(v));
}
url.search = params.toString(); // URLSearchParams -> querystring [web:87]
try {
const response = await fetch(url.toString(), { method: "GET" });
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
// WP REST почти всегда JSON
return (await response.json()) as T;
} catch (error) {
if (error instanceof Error) {
console.error("WP REST GET request failed:", error.message);
throw error;
}
throw new Error("Unknown error in WP REST GET request");
}
}