File size: 1,035 Bytes
1794757 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | 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;
}
}
|