StarrySkyWorld's picture
Init
8820bb8
raw
history blame contribute delete
749 Bytes
const TOKEN_KEY = "ffv_token";
export function setToken(token) {
localStorage.setItem(TOKEN_KEY, token);
}
export function getToken() {
return localStorage.getItem(TOKEN_KEY) || "";
}
export function clearToken() {
localStorage.removeItem(TOKEN_KEY);
}
export async function api(path, options = {}) {
const token = getToken();
const headers = {
...(options.headers || {}),
};
if (!(options.body instanceof FormData)) {
headers["Content-Type"] = "application/json";
}
if (token) {
headers.Authorization = `Bearer ${token}`;
}
const res = await fetch(path, { ...options, headers });
if (!res.ok) {
const text = await res.text();
throw new Error(text || `HTTP ${res.status}`);
}
return res.json();
}