Files
verify/frontend/lib/api.ts
Mohamed Mathar Irfan ed6610d5d8 Initial project upload
2026-07-28 17:57:02 +05:30

42 lines
1010 B
TypeScript

const API = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000";
function getToken(): string | null {
if (typeof window === "undefined") return null;
return window.localStorage.getItem("vp_token");
}
export function setToken(token: string) {
window.localStorage.setItem("vp_token", token);
}
export function clearToken() {
window.localStorage.removeItem("vp_token");
}
export async function api<T = any>(
path: string,
opts: RequestInit = {}
): Promise<T> {
const token = getToken();
const res = await fetch(`${API}${path}`, {
...opts,
headers: {
"Content-Type": "application/json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
...(opts.headers || {}),
},
});
if (!res.ok) {
let detail: any = res.statusText;
try {
detail = (await res.json()).detail ?? detail;
} catch {}
throw { status: res.status, detail };
}
if (res.status === 204) return undefined as T;
return res.json();
}
export const apiBase = API;