交付双端基础、实时联系人和隔离浏览器
This commit is contained in:
1 parent
43687d5e7e
commit
67fef3ff87
59 files changed
+5094
-1
No files matched your search
@@ -0,0 +1,32 @@
|
||||
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])
|
||||
}
|
||||
Reference in new issue
Block a user