admin / Apex
publicBid Management and Orchestration Tool with AI Capability
Apex / Synapse-Apexv2 / frontend / src / lib / api.ts
1864 B · main
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | let token: string | null = localStorage.getItem("apex_token"); export function setToken(t: string | null) { token = t; if (t) localStorage.setItem("apex_token", t); else localStorage.removeItem("apex_token"); } export function getToken() { return token; } async function req(method: string, path: string, body?: any, isForm = false) { const headers: Record<string, string> = {}; if (token) headers["Authorization"] = `Bearer ${token}`; let payload: any = undefined; if (body !== undefined) { if (isForm) { payload = body; } else { headers["Content-Type"] = "application/json"; payload = JSON.stringify(body); } } const res = await fetch(`/api${path}`, { method, headers, body: payload }); if (!res.ok) { let msg = res.statusText; try { const j = await res.json(); msg = j.detail || j.error?.message || msg; } catch {} throw new Error(msg); } const ct = res.headers.get("content-type") || ""; if (ct.includes("application/json")) return res.json(); return res; } export const api = { get: (p: string) => req("GET", p), post: (p: string, b?: any) => req("POST", p, b), patch: (p: string, b?: any) => req("PATCH", p, b), put: (p: string, b?: any) => req("PUT", p, b), del: (p: string) => req("DELETE", p), postForm: (p: string, form: FormData) => req("POST", p, form, true), download: async (p: string, filename: string) => { const headers: Record<string, string> = {}; if (token) headers["Authorization"] = `Bearer ${token}`; const res = await fetch(`/api${p}`, { headers }); if (!res.ok) throw new Error("Download failed"); const blob = await res.blob(); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = filename; a.click(); URL.revokeObjectURL(url); }, }; |