Files
kashilo/js/services/api.js
2026-01-28 07:02:55 +01:00

139 lines
3.4 KiB
JavaScript

const API_BASE_URL = '/api';
class ApiService {
constructor() {
this.baseUrl = API_BASE_URL;
this.token = null;
}
setToken(token) {
this.token = token;
}
clearToken() {
this.token = null;
}
async request(endpoint, options = {}) {
const url = `${this.baseUrl}${endpoint}`;
const headers = {
'Content-Type': 'application/json',
...options.headers
};
if (this.token) {
headers['Authorization'] = `Bearer ${this.token}`;
}
try {
const response = await fetch(url, {
...options,
headers
});
if (!response.ok) {
const error = await response.json().catch(() => ({}));
throw new ApiError(response.status, error.message || 'Request failed', error);
}
if (response.status === 204) {
return null;
}
return await response.json();
} catch (error) {
if (error instanceof ApiError) throw error;
throw new ApiError(0, 'Network error', { originalError: error });
}
}
async get(endpoint, params = {}) {
const queryString = new URLSearchParams(params).toString();
const url = queryString ? `${endpoint}?${queryString}` : endpoint;
return this.request(url, { method: 'GET' });
}
async post(endpoint, data) {
return this.request(endpoint, {
method: 'POST',
body: JSON.stringify(data)
});
}
async put(endpoint, data) {
return this.request(endpoint, {
method: 'PUT',
body: JSON.stringify(data)
});
}
async patch(endpoint, data) {
return this.request(endpoint, {
method: 'PATCH',
body: JSON.stringify(data)
});
}
async delete(endpoint) {
return this.request(endpoint, { method: 'DELETE' });
}
async getListings(params = {}) {
return this.get('/items/listings', params);
}
async getListing(id) {
return this.get(`/items/listings/${id}`);
}
async createListing(data) {
return this.post('/items/listings', data);
}
async updateListing(id, data) {
return this.patch(`/items/listings/${id}`, data);
}
async deleteListing(id) {
return this.delete(`/items/listings/${id}`);
}
async searchListings(query, params = {}) {
return this.get('/items/listings', { search: query, ...params });
}
async getCategories() {
return this.get('/items/categories');
}
async uploadFile(file) {
const formData = new FormData();
formData.append('file', file);
const response = await fetch(`${this.baseUrl}/files`, {
method: 'POST',
headers: this.token ? { 'Authorization': `Bearer ${this.token}` } : {},
body: formData
});
if (!response.ok) {
throw new ApiError(response.status, 'Upload failed');
}
return response.json();
}
}
class ApiError extends Error {
constructor(status, message, data = {}) {
super(message);
this.name = 'ApiError';
this.status = status;
this.data = data;
}
}
export const api = new ApiService();
export { ApiError };