| super(message || statusText) |
| 9 | this.status = status |
| 10 | this.statusText = statusText |
| 11 | } |
| 12 | } |
| 13 |
| 14 | async function request<T>(url: string, options: RequestInit = {}): Promise<T> { |
| 15 | const defaultOptions: RequestInit = { |
| 16 | credentials: 'include', |
| 17 | } |
| 18 |
| 19 | const response = await fetch(url, { ...defaultOptions, ...options }) |
| 20 |
| 21 | if (!response.ok) { |
| 22 | throw new HTTPError( |
| 23 | response.status, |
| 24 | response.statusText, |
| 25 | `HTTP ${response.status}`, |
| 26 | ) |
| 27 | } |
| 28 |
| 29 | // Handle empty response (e.g. 204 No Content) |
| 30 | if (response.status === 204) { |
| 31 | return {} as T |
| 32 | } |
| 33 |
| 34 | const contentType = response.headers.get('content-type') |
| 35 | if (contentType && contentType.includes('application/json')) { |
| 36 | return response.json() |
| 37 | } |
| 38 | return response.text() as unknown as T |
| 39 | } |
| 40 |
| 41 | export const http = { |
| 42 | get: <T>(url: string, options?: RequestInit) => |
| 43 | request<T>(url, { ...options, method: 'GET' }), |
| 44 | post: <T>(url: string, body?: any, options?: RequestInit) => { |
| 45 | const headers: HeadersInit = { ...options?.headers } |
| 46 | let requestBody = body |
| 47 |
| 48 | if ( |
| 49 | body && |
| 50 | typeof body === 'object' && |
| 51 | !(body instanceof FormData) && |
| 52 | !(body instanceof Blob) |
| 53 | ) { |
| 54 | if (!('Content-Type' in headers)) { |
| 55 | ;(headers as any)['Content-Type'] = 'application/json' |
| 56 | } |
| 57 | requestBody = JSON.stringify(body) |
| 58 | } |
| 59 |
| 60 | return request<T>(url, { |
| 61 | ...options, |
| 62 | method: 'POST', |
| 63 | headers, |
| 64 | body: requestBody, |
| 65 | }) |
| 66 | }, |
| 67 | put: <T>(url: string, body?: any, options?: RequestInit) => { |
| 68 | const headers: HeadersInit = { ...options?.headers } |
| 69 | let requestBody = body |
| 70 |
| 71 | if ( |
| 72 | body && |
| 73 | typeof body === 'object' && |
| 74 | !(body instanceof FormData) && |
| 75 | !(body instanceof Blob) |
| 76 | ) { |
| 77 | if (!('Content-Type' in headers)) { |
| 78 | ;(headers as any)['Content-Type'] = 'application/json' |
| 79 | } |
| 80 | requestBody = JSON.stringify(body) |
| 81 | } |
| 82 |
| 83 | return request<T>(url, { |
| 84 | ...options, |
| 85 | method: 'PUT', |
| 86 | headers, |
| 87 | body: requestBody, |
| 88 | }) |
| 89 | }, |
| 90 | delete: <T>(url: string, options?: RequestInit) => |
| 91 | request<T>(url, { ...options, method: 'DELETE' }), |
| 92 | } |