NeonClary's picture
Deploy tutorial feature and recent fixes
d8808e7 verified
Raw
History Blame Contribute Delete
850 Bytes
const base = import.meta.env.VITE_API_URL || ''
export function apiUrl(path: string): string {
if (path.startsWith('http')) return path
const p = path.startsWith('/') ? path : `/${path}`
return base ? `${base.replace(/\/$/, '')}${p}` : p
}
export function getToken(): string | null {
return localStorage.getItem('authToken')
}
export async function apiFetch(
path: string,
options: RequestInit & { auth?: boolean } = {},
): Promise<Response> {
const headers = new Headers(options.headers)
if (!headers.has('Content-Type') && options.body && typeof options.body === 'string') {
headers.set('Content-Type', 'application/json')
}
if (options.auth !== false) {
const t = getToken()
if (t) headers.set('Authorization', `Bearer ${t}`)
}
return fetch(apiUrl(path), { ...options, headers })
}