import type { RappiConfig } from "./schemas/config"; import { BASE_URL, DEFAULT_HEADERS } from "./constants"; function buildHeaders(config: RappiConfig): Record { return { ...DEFAULT_HEADERS, authorization: `Bearer ${config.token}`, deviceid: config.deviceId, }; } export async function get(path: string, config: RappiConfig): Promise { const res = await fetch(`${BASE_URL}${path}`, { headers: buildHeaders(config), }); if (!res.ok) throw new Error(`GET ${path} → ${res.status} ${res.statusText}`); return res.json(); } export async function post( path: string, body: unknown, config: RappiConfig ): Promise { const res = await fetch(`${BASE_URL}${path}`, { method: "POST", headers: { ...buildHeaders(config), "content-type": "application/json" }, body: JSON.stringify(body), }); if (!res.ok) { let errorBody = ""; try { errorBody = await res.text(); } catch {} const details = errorBody ? ` (${errorBody.substring(0, 100)})` : ""; throw new Error(`POST ${path} → ${res.status} ${res.statusText}${details}`); } return res.json(); } export async function put( path: string, body: unknown, config: RappiConfig ): Promise { const res = await fetch(`${BASE_URL}${path}`, { method: "PUT", headers: { ...buildHeaders(config), "content-type": "application/json" }, body: JSON.stringify(body), }); if (!res.ok) throw new Error(`PUT ${path} → ${res.status} ${res.statusText}`); return res.json(); } export async function del( path: string, config: RappiConfig ): Promise { const res = await fetch(`${BASE_URL}${path}`, { method: "DELETE", headers: buildHeaders(config), }); if (!res.ok) throw new Error(`DELETE ${path} → ${res.status} ${res.statusText}`); return res.json(); }