// services/api/client.js
const API_BASE = import.meta.env.VITE_API_URL || 'http://localhost:4000';
class ApiClient {
constructor(baseUrl) {
this.baseUrl = baseUrl;
}
async request(endpoint, options = {}) {
const url = `${this.baseUrl}${endpoint}`;
const config = {
headers: {
'Content-Type': 'application/json',
...options.headers,
},
...options,
};
// Add auth token if available
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
const response = await fetch(url, config);
if (!response.ok) {
const error = await response.json();
throw new ApiError(response.status, error.message);
}
return response.json();
}
get(endpoint) { return this.request(endpoint); }
post(endpoint, data) { return this.request(endpoint, { method: 'POST', body: JSON.stringify(data) }); }
put(endpoint, data) { return this.request(endpoint, { method: 'PUT', body: JSON.stringify(data) }); }
delete(endpoint) { return this.request(endpoint, { method: 'DELETE' }); }
}
export const api = new ApiClient(API_BASE);