calendi/app/lib/api/apiService.js
2025-05-01 20:31:20 +02:00

120 lines
2.8 KiB
JavaScript

import { Event } from '../models/Event';
const API_URL = 'http://calendi.test:88/api'; // Change this to your backend URL
/**
* Base API service for handling HTTP requests
*/
class ApiService {
/**
* Execute a fetch request with proper error handling
* @param {string} endpoint - API endpoint
* @param {Object} options - Fetch options
* @returns {Promise<any>} Response data
*/
async fetch(endpoint, options = {}) {
try {
const url = `${API_URL}${endpoint}`;
const defaultOptions = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
};
const response = await fetch(url, { ...defaultOptions, ...options });
if (!response.ok) {
throw new Error(`API request failed: ${response.status} ${response.statusText}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('API request error:', error);
throw error;
}
}
/**
* Get all events
* @returns {Promise<Event[]>} List of events
*/
async getEvents() {
const data = await this.fetch('/events');
return data.map(eventData => new Event(eventData));
}
/**
* Get a single event by ID
* @param {string} id - Event ID
* @returns {Promise<Event>} Event object
*/
async getEvent(id) {
const data = await this.fetch(`/events/${id}`);
return new Event(data);
}
/**
* Create a new event
* @param {Event} event - Event data
* @returns {Promise<Event>} Created event
*/
async createEvent(event) {
const data = await this.fetch('/events', {
method: 'POST',
body: JSON.stringify(event)
});
return new Event(data);
}
/**
* Update an existing event
* @param {string} id - Event ID
* @param {Event} event - Updated event data
* @returns {Promise<Event>} Updated event
*/
async updateEvent(id, event) {
const data = await this.fetch(`/events/${id}`, {
method: 'PUT',
body: JSON.stringify(event)
});
return new Event(data);
}
/**
* Delete an event
* @param {string} id - Event ID
* @returns {Promise<void>}
*/
async deleteEvent(id) {
await this.fetch(`/events/${id}`, {
method: 'DELETE'
});
}
/**
* Get user profile information
* @returns {Promise<Object>} User profile data
*/
async getUserProfile() {
return await this.fetch('/user/profile');
}
/**
* Update user profile
* @param {Object} profileData - Updated profile data
* @returns {Promise<Object>} Updated profile
*/
async updateUserProfile(profileData) {
return await this.fetch('/user/profile', {
method: 'PUT',
body: JSON.stringify(profileData)
});
}
}
// Create a singleton instance
const apiService = new ApiService();
export default apiService;