50 lines
1.3 KiB
TypeScript
50 lines
1.3 KiB
TypeScript
// Auto-generated API client for PetCare
|
|
|
|
import { API_BASE_URL, API_PREFIX } from "@shared/config";
|
|
|
|
const API_BASE = `${API_BASE_URL}${API_PREFIX}`;
|
|
|
|
interface RequestOptions extends RequestInit {
|
|
params?: Record<string, string | number>;
|
|
}
|
|
|
|
async function request<T>(endpoint: string, options: RequestOptions = {}): Promise<T> {
|
|
const { params, ...init } = options;
|
|
let url = `${API_BASE}${endpoint}`;
|
|
|
|
if (params) {
|
|
const searchParams = new URLSearchParams();
|
|
Object.entries(params).forEach(([k, v]) => searchParams.set(k, String(v)));
|
|
url += `?${searchParams.toString()}`;
|
|
}
|
|
|
|
const res = await fetch(url, {
|
|
...init,
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
...init.headers,
|
|
},
|
|
});
|
|
|
|
if (!res.ok) {
|
|
const err = await res.json().catch(() => ({ message: res.statusText }));
|
|
throw new Error(err.message || `API Error: ${res.status}`);
|
|
}
|
|
|
|
return res.json();
|
|
}
|
|
|
|
export const api = {
|
|
get: <T>(url: string, params?: Record<string, string | number>) =>
|
|
request<T>(url, { method: "GET", params }),
|
|
|
|
post: <T>(url: string, data?: unknown) =>
|
|
request<T>(url, { method: "POST", body: JSON.stringify(data) }),
|
|
|
|
put: <T>(url: string, data?: unknown) =>
|
|
request<T>(url, { method: "PUT", body: JSON.stringify(data) }),
|
|
|
|
delete: <T>(url: string) =>
|
|
request<T>(url, { method: "DELETE" }),
|
|
};
|