63 lines
1.6 KiB
TypeScript
63 lines
1.6 KiB
TypeScript
export class ApiClient {
|
|
private baseUrl: string;
|
|
|
|
constructor(baseUrl: string) {
|
|
this.baseUrl = baseUrl;
|
|
}
|
|
|
|
private async request<T>(method: string, path: string, data?: object): Promise<T | void> {
|
|
const headers: HeadersInit = {
|
|
'Content-Type': 'application/json',
|
|
};
|
|
|
|
const config: RequestInit = {
|
|
method,
|
|
headers,
|
|
};
|
|
|
|
if (data) {
|
|
config.body = JSON.stringify(data);
|
|
}
|
|
|
|
const response = await fetch(`${this.baseUrl}${path}`, config);
|
|
|
|
if (!response.ok) {
|
|
// Attempt to read error message from response body
|
|
let errorData: any;
|
|
try {
|
|
errorData = await response.json();
|
|
} catch (e) {
|
|
errorData = { message: response.statusText };
|
|
}
|
|
throw new Error(errorData.message || `API request failed with status ${response.status}`);
|
|
}
|
|
|
|
const text = await response.text();
|
|
return text ? JSON.parse(text) : undefined;
|
|
}
|
|
|
|
get<T>(path: string): Promise<T | void> {
|
|
return this.request<T>('GET', path);
|
|
}
|
|
|
|
post<T>(path: string, data: object): Promise<T | void> {
|
|
return this.request<T>('POST', path, data);
|
|
}
|
|
|
|
put<T>(path: string, data: object): Promise<T | void> {
|
|
return this.request<T>('PUT', path, data);
|
|
}
|
|
|
|
delete<T>(path: string): Promise<T | void> {
|
|
return this.request<T>('DELETE', path);
|
|
}
|
|
|
|
patch<T>(path: string, data: object): Promise<T | void> {
|
|
return this.request<T>('PATCH', path, data);
|
|
}
|
|
}
|
|
|
|
// Instantiate the API client with your backend's base URL
|
|
// You might want to get this from an environment variable
|
|
export const api = new ApiClient(process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:3001');
|