Files
2026-03-25 12:29:03 -05:00

32 lines
939 B
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { BindPayload } from './types'
function joinUrl(base: string, path: string): string {
const b = base.replace(/\/$/, '')
const p = path.startsWith('/') ? path : `/${path}`
return `${b}${p}`
}
export async function apiFetch(
bind: BindPayload | null,
path: string,
init?: RequestInit,
): Promise<Response> {
if (!bind) {
return Promise.reject(new Error('尚未绑定 PC请先在「配对」扫码'))
}
const headers = new Headers(init?.headers)
if (bind.token?.trim()) {
headers.set('Authorization', `Bearer ${bind.token.trim()}`)
}
return fetch(joinUrl(bind.baseUrl, path), { ...init, headers })
}
export async function apiJson<T>(bind: BindPayload | null, path: string, init?: RequestInit): Promise<T> {
const res = await apiFetch(bind, path, init)
if (!res.ok) {
const t = await res.text()
throw new Error(t || `HTTP ${res.status}`)
}
return res.json() as Promise<T>
}