cut / frontend /src /lib /api.ts
Surf Studio
重写:SQLite + 独立循环 + 实时 Telegram + 一码一推 + 新页面
5936c9d
Raw History Blame Contribute Delete
1.52 kB
export function api(path: string) {
return `${import.meta.env.BASE_URL}api/${path.replace(/^\/+/, '')}`
}
const KEY_STORE = 'cut-admin-key'
export function getAdminKey() {
try {
return localStorage.getItem(KEY_STORE) || ''
} catch {
return ''
}
}
export function setAdminKey(key: string) {
try {
if (key) localStorage.setItem(KEY_STORE, key)
else localStorage.removeItem(KEY_STORE)
} catch {
/* private mode */
}
}
export class ApiError extends Error {
status: number
needsKey: boolean
constructor(message: string, status: number, needsKey = false) {
super(message)
this.status = status
this.needsKey = needsKey
}
}
/** JSON request helper; sends the saved admin key and turns error bodies into ApiError. */
export async function request<T = unknown>(path: string, init: { method?: string; body?: unknown } = {}): Promise<T> {
const headers: Record<string, string> = {}
const key = getAdminKey()
if (key) headers['x-admin-key'] = key
if (init.body !== undefined) headers['content-type'] = 'application/json'
const res = await fetch(api(path), {
method: init.method || (init.body !== undefined ? 'POST' : 'GET'),
headers,
body: init.body !== undefined ? JSON.stringify(init.body) : undefined,
})
let body: any = null
try {
body = await res.json()
} catch {
/* empty body */
}
if (!res.ok) throw new ApiError(body?.error || `请求失败(${res.status})`, res.status, Boolean(body?.needsKey))
return body as T
}