http.ts (1398B)
1 export interface ApiError extends Error { 2 code?: string; 3 status?: number; 4 } 5 6 export function toApiError(payload: any, response: Response): ApiError { 7 const error = new Error( 8 payload?.error_description || 9 payload?.error?.message || 10 response.statusText 11 ) as ApiError; 12 error.code = payload?.error?.code || payload?.error; 13 error.status = response.status; 14 return error; 15 } 16 17 export async function parseJsonResponse<T>(response: Response): Promise<T> { 18 let payload: any = null; 19 try { 20 payload = await response.json(); 21 } catch { 22 payload = null; 23 } 24 if (!response.ok) throw toApiError(payload, response); 25 return payload as T; 26 } 27 28 export async function requestJson<T>(path: string, init: RequestInit = {}): Promise<T> { 29 const headers = new Headers(init.headers); 30 if (!headers.has('content-type')) headers.set('content-type', 'application/json'); 31 const response = await fetch(path, { 32 credentials: 'same-origin', 33 ...init, 34 headers, 35 }); 36 return parseJsonResponse<T>(response); 37 } 38 39 export async function formRequest<T>( 40 url: string, 41 values: Record<string, string> 42 ): Promise<T> { 43 const response = await fetch(url, { 44 method: 'POST', 45 credentials: 'omit', 46 headers: { 47 'content-type': 'application/x-www-form-urlencoded', 48 }, 49 body: new URLSearchParams(values).toString(), 50 }); 51 return parseJsonResponse<T>(response); 52 }