36 lines
1 KiB
TypeScript
36 lines
1 KiB
TypeScript
export class ApiError extends Error {
|
|
constructor(public readonly statusCode: number, message: string) {
|
|
super(message);
|
|
this.name = "ApiError";
|
|
}
|
|
}
|
|
|
|
export class BaseApi {
|
|
constructor(protected readonly baseUrl: string) {}
|
|
|
|
protected async request<T>(
|
|
endpoint: string,
|
|
options: {
|
|
method: string,
|
|
headers: Record<string, string>,
|
|
body?: string
|
|
}
|
|
): Promise<T> {
|
|
const url = `${this.baseUrl}${endpoint}`;
|
|
const res = await fetch(url, options);
|
|
|
|
if (!res.ok) {
|
|
// Log the error response for debugging
|
|
console.error(`Failed with ${res.status} ${res.statusText}`);
|
|
const errorText = await res.json();
|
|
console.error("Response:", errorText);
|
|
|
|
throw new ApiError(res.status, errorText.message);
|
|
}
|
|
if (res.status === 204) {
|
|
return undefined as T; // No content: ;
|
|
}
|
|
const data = await res.json();
|
|
return data as T;
|
|
}
|
|
}
|