| export class HttpError extends Error { | |
| readonly status: number; | |
| constructor(status: number, message: string) { | |
| super(message); | |
| this.name = "HttpError"; | |
| this.status = status; | |
| } | |
| } | |
| export class HttpClient { | |
| constructor(private readonly baseUrl: string) {} | |
| async get<T>(path: string): Promise<T> { | |
| return this.request<T>(path, { method: "GET" }); | |
| } | |
| async post<T>(path: string, body?: unknown): Promise<T> { | |
| return this.request<T>(path, { | |
| method: "POST", | |
| body: body === undefined ? undefined : JSON.stringify(body), | |
| }); | |
| } | |
| private async request<T>(path: string, init: RequestInit): Promise<T> { | |
| const response = await fetch(`${this.baseUrl}${path}`, { | |
| ...init, | |
| headers: { | |
| "Content-Type": "application/json", | |
| ...(init.headers || {}), | |
| }, | |
| }); | |
| if (!response.ok) { | |
| const message = await response.text(); | |
| throw new HttpError(response.status, message || response.statusText); | |
| } | |
| return (await response.json()) as T; | |
| } | |
| } | |