Files
XHChat/web/src/api.ts
T

33 lines
1.2 KiB
TypeScript

const base = window.xhchat?.apiBase ?? ''
export class APIError extends Error {
constructor(public status: number, message: string) {
super(message)
}
}
export async function request<T>(path: string, method = 'GET', token = '', body?: object): Promise<T> {
const headers: Record<string, string> = { Accept: 'application/json' }
if (token) headers.Authorization = 'Bearer ' + token
if (body) headers['Content-Type'] = 'application/json'
let response: Response
try {
response = await fetch(base + '/api/v1' + path, {
method, headers, body: body ? JSON.stringify(body) : undefined,
credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(12000),
})
} catch {
throw new Error('无法连接 XHChat 服务,请检查网络后重试')
}
if (response.status === 204) return undefined as T
const data = await response.json().catch(() => null)
if (!response.ok) throw new APIError(response.status, data?.error?.message ?? '请求失败,请稍后重试')
return data as T
}
export function realtime(ticket: string) {
const url = new URL((base || location.origin) + '/api/v1/realtime')
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
return new WebSocket(url, ['xhchat.v1', 'ticket.' + ticket])
}