File
Blob: ui/shared/http.ts
| 1 | export class RequestError extends Error { |
| 2 | constructor( |
| 3 | message: string, |
| 4 | readonly code = 'request_failed', |
| 5 | readonly data?: Record<string, unknown>, |
| 6 | readonly status = 0, |
| 7 | ) { super(message); } |
| 8 | |
| 9 | get fields(): Record<string, string> { |
| 10 | return this.data?.fields && typeof this.data.fields === 'object' |
| 11 | ? this.data.fields as Record<string, string> : {}; |
| 12 | } |
| 13 | } |
| 14 | |
| 15 | export function errorMessage(error: unknown): string { |
| 16 | return error instanceof Error ? error.message : 'Request failed.'; |
| 17 | } |
| 18 | |
| 19 | export async function requestJSON<T>(url: string, options: RequestInit & { timeout?: number } = {}): Promise<T> { |
| 20 | const { timeout = 12_000, signal, ...init } = options; |
| 21 | const deadline = AbortSignal.timeout(timeout); |
| 22 | const writing = !['GET', 'HEAD'].includes(init.method ?? 'GET'); |
| 23 | const headers = new Headers(init.headers); |
| 24 | headers.set('Accept', 'application/json'); |
| 25 | if (init.body && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json'); |
| 26 | try { |
| 27 | const response = await fetch(url, { |
| 28 | credentials: 'same-origin', cache: 'no-store', ...init, headers, |
| 29 | signal: signal ? AbortSignal.any([signal, deadline]) : deadline, |
| 30 | }); |
| 31 | const text = await response.text(); |
| 32 | let data: unknown; |
| 33 | try { data = text ? JSON.parse(text) : null; } catch { data = null; } |
| 34 | if (!response.ok) { |
| 35 | const detail = data && typeof data === 'object' && !Array.isArray(data) ? data as Record<string, unknown> : undefined; |
| 36 | const message = detail?.message ?? detail?.error ?? detail?.msg; |
| 37 | throw new RequestError( |
| 38 | typeof message === 'string' ? message : text.trim() || `Server returned ${response.status}.`, |
| 39 | typeof detail?.code === 'string' ? detail.code : writing && response.status >= 500 ? 'outcome_unknown' : 'request_failed', |
| 40 | detail, response.status, |
| 41 | ); |
| 42 | } |
| 43 | return data as T; |
| 44 | } catch (cause) { |
| 45 | if (cause instanceof RequestError) throw cause; |
| 46 | throw new RequestError(deadline.aborted ? 'Request timed out.' : errorMessage(cause), writing ? 'outcome_unknown' : 'request_failed'); |
| 47 | } |
| 48 | } |