2026-04-14 21:48:53 +08:00
|
|
|
import router from '@/router'
|
|
|
|
|
|
2026-04-11 15:59:14 +08:00
|
|
|
const DEFAULT_BASE_URL = ''
|
|
|
|
|
|
|
|
|
|
function getBaseUrl(): string {
|
|
|
|
|
return localStorage.getItem('hermes_server_url') || DEFAULT_BASE_URL
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-15 09:13:27 +08:00
|
|
|
export function getApiKey(): string {
|
2026-04-11 15:59:14 +08:00
|
|
|
return localStorage.getItem('hermes_api_key') || ''
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function setServerUrl(url: string) {
|
|
|
|
|
localStorage.setItem('hermes_server_url', url)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function setApiKey(key: string) {
|
|
|
|
|
localStorage.setItem('hermes_api_key', key)
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-14 21:48:53 +08:00
|
|
|
export function clearApiKey() {
|
|
|
|
|
localStorage.removeItem('hermes_api_key')
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function hasApiKey(): boolean {
|
|
|
|
|
return !!getApiKey()
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-11 15:59:14 +08:00
|
|
|
export async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
|
|
|
|
|
const base = getBaseUrl()
|
|
|
|
|
const url = `${base}${path}`
|
|
|
|
|
const headers: Record<string, string> = {
|
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
|
...options.headers as Record<string, string>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const apiKey = getApiKey()
|
|
|
|
|
if (apiKey) {
|
|
|
|
|
headers['Authorization'] = `Bearer ${apiKey}`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const res = await fetch(url, { ...options, headers })
|
|
|
|
|
|
2026-04-15 11:00:47 +08:00
|
|
|
// Global 401 handler — clear auth and redirect to login
|
2026-04-14 21:48:53 +08:00
|
|
|
if (res.status === 401) {
|
2026-04-15 11:00:47 +08:00
|
|
|
clearApiKey()
|
|
|
|
|
if (router.currentRoute.value.name !== 'login') {
|
|
|
|
|
router.replace({ name: 'login' })
|
|
|
|
|
}
|
2026-04-14 21:48:53 +08:00
|
|
|
throw new Error('Unauthorized')
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-11 15:59:14 +08:00
|
|
|
if (!res.ok) {
|
|
|
|
|
const text = await res.text().catch(() => '')
|
|
|
|
|
throw new Error(`API Error ${res.status}: ${text || res.statusText}`)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return res.json()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function getBaseUrlValue(): string {
|
|
|
|
|
return getBaseUrl()
|
|
|
|
|
}
|