Files
XHChat/web/src/api.ts
T

52 lines
2.0 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, binary = false): Promise<T> {
const headers: Record<string, string> = { Accept: 'application/json' }
if (token) headers.Authorization = 'Bearer ' + token
const bytes = body instanceof ArrayBuffer
if (body) headers['Content-Type'] = bytes ? 'application/octet-stream' : 'application/json'
let response: Response
try {
response = await fetch(base + '/api/v1' + path, {
method, headers, body: bytes ? body : body ? JSON.stringify(body) : undefined,
credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(binary || bytes ? 60_000 : 12_000),
})
} catch {
throw new Error('无法连接 XHChat 服务,请检查网络后重试')
}
if (response.status === 204) return undefined as T
if (binary && response.ok) {
if (Number(response.headers.get('Content-Length')) > 8 * 1024 * 1024 + 16) throw new Error('附件超过大小限制')
const reader = response.body?.getReader()
if (!reader) throw new Error('附件下载失败')
const chunks: Uint8Array<ArrayBuffer>[] = []
let length = 0
for (;;) {
const { value, done } = await reader.read()
if (done) break
length += value.byteLength
if (length > 8 * 1024 * 1024 + 16) {
await reader.cancel()
throw new Error('附件超过大小限制')
}
chunks.push(value)
}
return await new Blob(chunks).arrayBuffer() 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])
}