UNPKG

dengun_ai-admin-client

Version:

Cliente simples para integração com o AI Admin Dashboard - Plug and Play

170 lines (169 loc) 5.56 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ConnectionManager = void 0; const events_1 = require("events"); const axios_1 = __importDefault(require("axios")); /** * Objetivo 1: Gerenciar conexão entre a app externa e o AI Admin Dashboard */ class ConnectionManager extends events_1.EventEmitter { constructor(config) { var _a; super(); this.isConnected = false; this.pingInterval = null; this.authToken = null; this.lastPing = 0; this.config = config; this.httpClient = axios_1.default.create({ baseURL: config.dashboardUrl, timeout: ((_a = config.options) === null || _a === void 0 ? void 0 : _a.timeout) || 10000, headers: { 'Content-Type': 'application/json' } }); this.setupInterceptors(); } /** * Estabelecer conexão com o dashboard */ async connect() { var _a, _b; try { // Autenticar bot const authResponse = await this.httpClient.post('/api/bots/auth', { botId: this.config.botId, botSecret: this.config.botSecret }); if (!((_a = authResponse.data) === null || _a === void 0 ? void 0 : _a.success)) { throw new Error(((_b = authResponse.data) === null || _b === void 0 ? void 0 : _b.error) || 'Falha na autenticação'); } this.authToken = authResponse.data.token; this.isConnected = true; this.lastPing = Date.now(); // Iniciar ping periódico this.startPingInterval(); this.emit('connected'); } catch (error) { this.isConnected = false; this.emit('error', error); throw error; } } /** * Desconectar do dashboard */ async disconnect() { this.stopPingInterval(); this.isConnected = false; this.authToken = null; this.emit('disconnected'); } /** * Validar se usuário pode usar o bot */ async validateUser(userId, tenantId) { try { const response = await this.httpClient.post('/api/bots/validate-user', { userId, tenantId, botId: this.config.botId }); return response.data; } catch (error) { return { success: false, error: error instanceof Error ? error.message : 'Erro ao validar usuário' }; } } /** * Enviar dados para o dashboard */ async sendData(endpoint, data) { try { const response = await this.httpClient.post(endpoint, data); return response.data; } catch (error) { return { success: false, error: error instanceof Error ? error.message : 'Erro ao enviar dados' }; } } /** * Obter status da conexão */ getStatus() { return { connected: this.isConnected, authenticated: !!this.authToken, lastPing: this.lastPing, error: this.isConnected ? undefined : 'Não conectado' }; } /** * Verificar se está conectado */ isConnectionActive() { return this.isConnected && !!this.authToken; } // Métodos privados setupInterceptors() { // Interceptor para adicionar token de auth this.httpClient.interceptors.request.use((config) => { if (this.authToken) { config.headers.Authorization = `Bearer ${this.authToken}`; } return config; }); // Interceptor para tratar erros de auth this.httpClient.interceptors.response.use((response) => response, async (error) => { var _a; if (((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) === 401) { // Token expirado, tentar reconectar this.authToken = null; this.isConnected = false; this.emit('authExpired'); // Tentar reconectar automaticamente try { await this.connect(); } catch (reconnectError) { this.emit('error', reconnectError); } } return Promise.reject(error); }); } startPingInterval() { this.stopPingInterval(); this.pingInterval = setInterval(async () => { try { await this.httpClient.get('/api/bots/ping'); this.lastPing = Date.now(); } catch (error) { this.emit('pingFailed', error); // Se ping falhar múltiplas vezes, considerar desconectado if (Date.now() - this.lastPing > 120000) { // 2 minutos this.isConnected = false; this.emit('disconnected'); } } }, 30000); // Ping a cada 30 segundos } stopPingInterval() { if (this.pingInterval) { clearInterval(this.pingInterval); this.pingInterval = null; } } } exports.ConnectionManager = ConnectionManager;