32 lines
939 B
TypeScript
32 lines
939 B
TypeScript
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>
|
||
}
|