105 lines
2.1 KiB
JavaScript
105 lines
2.1 KiB
JavaScript
|
|
const API_URL = 'http://localhost:8080/api';
|
||
|
|
|
||
|
|
class ApiError extends Error {
|
||
|
|
constructor(message, status, data) {
|
||
|
|
super(message);
|
||
|
|
this.name = 'ApiError';
|
||
|
|
this.status = status;
|
||
|
|
this.data = data;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
async function fetchAPI(endpoint, options = {}) {
|
||
|
|
const url = `${API_URL}${endpoint}`;
|
||
|
|
|
||
|
|
const config = {
|
||
|
|
...options,
|
||
|
|
headers: {
|
||
|
|
'Content-Type': 'application/json',
|
||
|
|
...options.headers,
|
||
|
|
},
|
||
|
|
};
|
||
|
|
|
||
|
|
// Add auth token if available
|
||
|
|
const token = localStorage.getItem('token');
|
||
|
|
if (token) {
|
||
|
|
config.headers['Authorization'] = `Bearer ${token}`;
|
||
|
|
}
|
||
|
|
|
||
|
|
try {
|
||
|
|
const response = await fetch(url, config);
|
||
|
|
const data = await response.json();
|
||
|
|
|
||
|
|
if (!response.ok) {
|
||
|
|
throw new ApiError(
|
||
|
|
data.error || 'API request failed',
|
||
|
|
response.status,
|
||
|
|
data
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
return data;
|
||
|
|
} catch (error) {
|
||
|
|
if (error instanceof ApiError) {
|
||
|
|
throw error;
|
||
|
|
}
|
||
|
|
throw new ApiError('Network error', 0, { message: error.message });
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// Auth API
|
||
|
|
export const authAPI = {
|
||
|
|
async register(username, email, password) {
|
||
|
|
const data = await fetchAPI('/auth/register', {
|
||
|
|
method: 'POST',
|
||
|
|
body: JSON.stringify({ username, email, password }),
|
||
|
|
});
|
||
|
|
|
||
|
|
// Save token
|
||
|
|
if (data.data.token) {
|
||
|
|
localStorage.setItem('token', data.data.token);
|
||
|
|
}
|
||
|
|
|
||
|
|
return data.data;
|
||
|
|
},
|
||
|
|
|
||
|
|
async login(email, password) {
|
||
|
|
const data = await fetchAPI('/auth/login', {
|
||
|
|
method: 'POST',
|
||
|
|
body: JSON.stringify({ email, password }),
|
||
|
|
});
|
||
|
|
|
||
|
|
// Save token
|
||
|
|
if (data.data.token) {
|
||
|
|
localStorage.setItem('token', data.data.token);
|
||
|
|
}
|
||
|
|
|
||
|
|
return data.data;
|
||
|
|
},
|
||
|
|
|
||
|
|
async getCurrentUser() {
|
||
|
|
const data = await fetchAPI('/users/me');
|
||
|
|
return data.data;
|
||
|
|
},
|
||
|
|
|
||
|
|
logout() {
|
||
|
|
localStorage.removeItem('token');
|
||
|
|
localStorage.removeItem('user');
|
||
|
|
},
|
||
|
|
};
|
||
|
|
|
||
|
|
// Events API
|
||
|
|
export const eventsAPI = {
|
||
|
|
async getAll() {
|
||
|
|
const data = await fetchAPI('/events');
|
||
|
|
return data.data;
|
||
|
|
},
|
||
|
|
|
||
|
|
async getById(id) {
|
||
|
|
const data = await fetchAPI(`/events/${id}`);
|
||
|
|
return data.data;
|
||
|
|
},
|
||
|
|
};
|
||
|
|
|
||
|
|
export { ApiError };
|