import { API_CONFIG, DEFAULT_REQUEST_CONFIG } from '@/config/api.js'; import AuthService from '@/service/AuthService.js'; import { ChannelDto, ChannelType } from '@/types/smm.js'; /** * ChannelService - Управление каналами * Базовый путь: /api/smm/channels */ class ChannelService { constructor() { this.baseUrl = API_CONFIG.SMM_BASE_URL; this.endpoints = { channels: API_CONFIG.ENDPOINTS.CHANNELS, channelById: API_CONFIG.ENDPOINTS.CHANNEL_BY_ID }; } /** * Получить все каналы * GET /api/smm/channels * @returns {Promise} */ async getAllChannels() { try { const response = await AuthService.authFetch(`${this.baseUrl}${this.endpoints.channels}`, { method: 'GET', headers: { ...DEFAULT_REQUEST_CONFIG.headers } }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); return data.map((channel) => new ChannelDto(channel)); } catch (error) { console.error('Error fetching channels:', error); throw error; } } /** * Получить канал по ID * GET /api/smm/channels/{id} * @param {string} id - UUID канала * @returns {Promise} */ async getChannelById(id) { try { const response = await AuthService.authFetch(`${this.baseUrl}${this.endpoints.channelById}/${id}`, { method: 'GET', headers: { ...DEFAULT_REQUEST_CONFIG.headers } }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); return new ChannelDto(data); } catch (error) { console.error(`Error fetching channel ${id}:`, error); throw error; } } /** * Создать канал * POST /api/smm/channels * @param {Object} channelData - Данные канала * @param {string} channelData.name - Название канала * @param {string} channelData.type - Тип канала (TELEGRAM, VK, INSTAGRAM) * @param {string} channelData.apiKeyRef - Ссылка на API ключ * @param {boolean} channelData.isActive - Активен ли канал * @returns {Promise} */ async createChannel(channelData) { try { // Валидация this.validateChannelData(channelData); const response = await AuthService.authFetch(`${this.baseUrl}${this.endpoints.channels}`, { method: 'POST', headers: { ...DEFAULT_REQUEST_CONFIG.headers }, body: JSON.stringify(channelData) }); if (!response.ok) { const errorData = await response.json(); throw new Error(`HTTP error! status: ${response.status}, message: ${errorData.message || 'Unknown error'}`); } const data = await response.json(); return new ChannelDto(data); } catch (error) { console.error('Error creating channel:', error); throw error; } } /** * Обновить канал * PUT /api/smm/channels/{id} * @param {string} id - UUID канала * @param {Object} channelData - Данные канала * @returns {Promise} */ async updateChannel(id, channelData) { try { // Валидация this.validateChannelData(channelData); const response = await AuthService.authFetch(`${this.baseUrl}${this.endpoints.channelById}/${id}`, { method: 'PUT', headers: { ...DEFAULT_REQUEST_CONFIG.headers }, body: JSON.stringify(channelData) }); if (!response.ok) { const errorData = await response.json(); throw new Error(`HTTP error! status: ${response.status}, message: ${errorData.message || 'Unknown error'}`); } const data = await response.json(); return new ChannelDto(data); } catch (error) { console.error(`Error updating channel ${id}:`, error); throw error; } } /** * Удалить канал * DELETE /api/smm/channels/{id} * @param {string} id - UUID канала * @returns {Promise} */ async deleteChannel(id) { try { const response = await AuthService.authFetch(`${this.baseUrl}${this.endpoints.channelById}/${id}`, { method: 'DELETE' }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } } catch (error) { console.error(`Error deleting channel ${id}:`, error); throw error; } } /** * Получить каналы по типу * @param {string} type - Тип канала * @returns {Promise} */ async getChannelsByType(type) { try { const allChannels = await this.getAllChannels(); return allChannels.filter((channel) => channel.type === type); } catch (error) { console.error(`Error fetching channels by type ${type}:`, error); throw error; } } /** * Получить активные каналы * @returns {Promise} */ async getActiveChannels() { try { const allChannels = await this.getAllChannels(); return allChannels.filter((channel) => channel.isActive); } catch (error) { console.error('Error fetching active channels:', error); throw error; } } /** * Валидация данных канала * @param {Object} channelData - Данные канала * @throws {Error} Если валидация не прошла */ validateChannelData(channelData) { if (!channelData.name || channelData.name.trim() === '') { throw new Error('Название канала обязательно'); } if (!channelData.type || !Object.values(ChannelType).includes(channelData.type)) { throw new Error('Тип канала обязателен и должен быть одним из: TELEGRAM, VK, INSTAGRAM'); } if (!channelData.apiKeyRef || channelData.apiKeyRef.trim() === '') { throw new Error('Ссылка на API ключ обязательна'); } if (typeof channelData.isActive !== 'boolean') { throw new Error('Поле isActive должно быть булевым значением'); } } } // Экспорт singleton instance export default new ChannelService();