67 lines
1.6 KiB
TypeScript
67 lines
1.6 KiB
TypeScript
import { API_BASE_URL } from '../constants/api';
|
|
import { ApiError } from '../types';
|
|
|
|
class ApiClient {
|
|
private baseUrl: string;
|
|
|
|
constructor(baseUrl: string) {
|
|
this.baseUrl = baseUrl;
|
|
}
|
|
|
|
private async request<T>(
|
|
endpoint: string,
|
|
options: RequestInit = {}
|
|
): Promise<T> {
|
|
const url = `${this.baseUrl}${endpoint}`;
|
|
const response = await fetch(url, {
|
|
...options,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
...options.headers,
|
|
},
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const error: ApiError = await response.json();
|
|
throw new Error(error.error?.message || 'Request failed');
|
|
}
|
|
|
|
return response.json();
|
|
}
|
|
|
|
async get<T>(endpoint: string): Promise<T> {
|
|
return this.request<T>(endpoint);
|
|
}
|
|
|
|
async post<T>(endpoint: string, body?: unknown): Promise<T> {
|
|
return this.request<T>(endpoint, {
|
|
method: 'POST',
|
|
body: body ? JSON.stringify(body) : undefined,
|
|
});
|
|
}
|
|
|
|
async delete<T>(endpoint: string): Promise<T> {
|
|
return this.request<T>(endpoint, { method: 'DELETE' });
|
|
}
|
|
|
|
async uploadFile<T>(endpoint: string, formData: FormData): Promise<T> {
|
|
const url = `${this.baseUrl}${endpoint}`;
|
|
const response = await fetch(url, {
|
|
method: 'POST',
|
|
body: formData,
|
|
headers: {
|
|
'Content-Type': 'multipart/form-data',
|
|
},
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const error: ApiError = await response.json();
|
|
throw new Error(error.error?.message || 'Upload failed');
|
|
}
|
|
|
|
return response.json();
|
|
}
|
|
}
|
|
|
|
export const apiClient = new ApiClient(API_BASE_URL);
|