UNPKG

varlet-fivem-api

Version:

A TypeScript/Node.js package to interact with FiveM servers, allowing you to retrieve server data, player information, and resources. Features intelligent caching system, supports IP/port, IP:port format, and CFX links. Built with TypeScript for better ty

360 lines (281 loc) 9.22 kB
# Discord FiveM API - Varlet A comprehensive and robust TypeScript library for interacting with FiveM servers, offering support for CFX links, intelligent caching, WebSocket, automatic retry, health monitoring, and multi-server management. ## 🚀 Features * ✅ **CFX Links Support** - Automatically accepts `cfx.re/join/xxx` links * ✅ **Intelligent Caching** - Configurable TTL caching system * ✅ **TypeScript** - Complete typing and IntelliSense * ✅ **WebSocket Support** - Real-time updates * ✅ **Retry & Fallback** - Circuit breaker pattern with automatic fallback * ✅ **Health Monitoring** - Health monitoring with alerts * ✅ **Multi-Server** - Multi-server management with load balancing * ✅ **Event-Driven** - Complete event system ## 📦 Installation ```bash npm install varlet-fivem-api ``` ## 🔧 Basic Configuration ### JavaScript ```javascript const { DiscordFivemApi } = require('varlet-fivem-api'); const api = new DiscordFivemApi({ address: '93.123.22.56:30120', useStructure: true, interval: 5000 }, true); api.on('ready', () => { console.log('API ready!'); }); ``` ### TypeScript ```typescript import { DiscordFivemApi } from 'varlet-fivem-api'; const api = new DiscordFivemApi({ address: '93.123.22.56:30120', useStructure: true, interval: 5000 }, true); api.on('ready', () => { console.log('API ready!'); }); ``` ## 🌐 CFX Links Support The library automatically accepts FiveM CFX links: ```javascript // All these formats work: const api1 = new DiscordFivemApi({ address: 'cfx.re/join/mkr5ov' }); const api2 = new DiscordFivemApi({ address: 'https://cfx.re/join/mkr5ov' }); const api3 = new DiscordFivemApi({ address: '93.123.22.56:30120' }); const api4 = new DiscordFivemApi({ address: '93.123.22.56', port: 30120 }); ``` ## 💾 Intelligent Caching System ```javascript const api = new DiscordFivemApi({ address: '93.123.22.56:30120', useStructure: true, // Cache settings cacheEnabled: true, cacheTTL: { serverData: 30000, // 30 seconds players: 10000, // 10 seconds status: 5000 // 5 seconds } }); // Check cache statistics const cacheStats = api.getCacheStats(); console.log('Cache hits:', cacheStats.hits); console.log('Cache misses:', cacheStats.misses); // Clear cache api.clearCache(); ``` ## 🔌 WebSocket Support ```javascript const api = new DiscordFivemApi({ address: '93.123.22.56:30120', useWebSocket: true, webSocketPort: 30120, webSocketTimeout: 10000, webSocketReconnectInterval: 5000, webSocketMaxReconnectAttempts: 5 }); // WebSocket events api.on('websocketConnect', () => { console.log('WebSocket connected!'); }); api.on('playerJoin', (player) => { console.log(`Player joined: ${player.name}`); }); api.on('playerLeave', (player) => { console.log(`Player left: ${player.name}`); }); api.on('serverUpdate', (data) => { console.log('Server updated:', data); }); ``` ## 🔄 Retry & Fallback with Circuit Breaker ```javascript const api = new DiscordFivemApi({ address: '93.123.22.56:30120', useStructure: true, // Retry settings maxRetries: 3, retryDelay: 1000, backoffMultiplier: 2, maxRetryDelay: 30000, // Circuit breaker circuitBreakerThreshold: 5, circuitBreakerTimeout: 60000, // Fallback endpoints fallbackEndpoints: [ '192.168.1.100:30120', '192.168.1.101:30120' ] }); // Retry events api.on('retry', (attempt, error) => { console.log(`Retry attempt ${attempt}:`, error.message); }); api.on('circuitBreakerOpen', () => { console.log('Circuit breaker opened - using fallback endpoints'); }); api.on('circuitBreakerClose', () => { console.log('Circuit breaker closed - back to normal operation'); }); ``` ## 🏥 Health Monitoring ```javascript const api = new DiscordFivemApi({ address: '93.123.22.56:30120', enableHealthMonitor: true, healthCheckInterval: 30000, healthCheckTimeout: 10000, healthCheckRetries: 3, healthAlertThreshold: 3, healthRecoveryThreshold: 2, healthAlertCooldown: 300000 }); // Health events api.on('healthCheck', (status) => { console.log('Health check:', status); }); api.on('alert', (alert) => { console.log(`Alert [${alert.severity}]:`, alert.message); }); // Get health status const healthStatus = api.getHealthStatus(); console.log('Current health:', healthStatus); ``` ## 🎮 Practical Examples ### Discord Bot with Monitoring ```javascript const { Client, GatewayIntentBits } = require('discord.js'); const { DiscordFivemApi } = require('varlet-fivem-api'); const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages] }); const api = new DiscordFivemApi({ address: 'cfx.re/join/mkr5ov', useStructure: true, enableHealthMonitor: true, healthCheckInterval: 30000 }); api.on('ready', () => { console.log('Monitoring FiveM server...'); }); api.on('playerJoin', (player) => { const channel = client.channels.cache.get('CHANNEL_ID'); channel.send(`🟢 **${player.name}** joined the server!`); }); api.on('playerLeave', (player) => { const channel = client.channels.cache.get('CHANNEL_ID'); channel.send(`🔴 **${player.name}** left the server!`); }); api.on('alert', (alert) => { if (alert.severity === 'HIGH' || alert.severity === 'CRITICAL') { const channel = client.channels.cache.get('ADMIN_CHANNEL_ID'); channel.send(`🚨 **Critical Alert**: ${alert.message}`); } }); client.login('YOUR_BOT_TOKEN'); ``` ### Web Dashboard with Multi-Server ```javascript const express = require('express'); const { MultiServerManager } = require('varlet-fivem-api'); const app = express(); const multiServerManager = new MultiServerManager({ servers: [ { id: 'main', name: 'Main Server', address: '93.123.22.56:30120' }, { id: 'backup', name: 'Backup Server', address: '192.168.1.100:30120' } ], loadBalancingStrategy: 'HEALTH_BASED' }); // General status endpoint app.get('/api/status', async (req, res) => { const stats = multiServerManager.getAggregatedStats(); res.json(stats); }); // All servers data endpoint app.get('/api/servers', async (req, res) => { const allData = await multiServerManager.getAllServerData(); const allPlayers = await multiServerManager.getAllServerPlayers(); res.json({ servers: allData, players: allPlayers }); }); // WebSocket for real-time updates const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); multiServerManager.on('serverHealthUpdate', (data) => { wss.clients.forEach(client => { if (client.readyState === WebSocket.OPEN) { client.send(JSON.stringify({ type: 'healthUpdate', data })); } }); }); app.listen(3000, () => { console.log('Dashboard running on port 3000'); }); ``` ## 🛠️ Available Scripts ```bash # Development npm run dev # Watch mode compilation npm run build # Compile TypeScript npm run type-check # Check types # Examples and Tests npm run test-interactive # Interactive test npm run example # Basic example npm run cache-demo # Cache system demo npm run websocket-demo # WebSocket demo npm run retry-demo # Retry system demo npm run resilience-test # Resilience test npm run health-monitor-demo # Health monitoring demo npm run multi-server-demo # Multi-server demo ``` ## 📝 TypeScript Types The library includes complete TypeScript types: ```typescript import { DiscordFivemApi, MultiServerManager, ServerOptions, PlayerInfo, ServerInfo, HealthStatus, HealthMetrics, Alert, LoadBalancingStats, AggregatedStats } from 'varlet-fivem-api'; // Example with typing const api: DiscordFivemApi = new DiscordFivemApi({ address: '93.123.22.56:30120' }); const players: PlayerInfo[] = await api.getServerPlayers(); const health: HealthStatus = api.getHealthStatus(); ``` ## 🤝 Contributing 1. Fork the project 2. Create a feature branch (`git checkout -b feature/AmazingFeature`) 3. Commit your changes (`git commit -m 'Add some AmazingFeature'`) 4. Push to the branch (`git push origin feature/AmazingFeature`) 5. Open a Pull Request ## 📄 License This project is licensed under the MIT License - see the LICENSE file for details. ## 🆘 Support * 📧 Email: support@varlet.com * 💬 Discord: Support Server * 📖 Documentation: docs.varlet.com * 🐛 Issues: GitHub Issues --- **Developed with ❤️ by Varlet for the FiveM community** ## About Varlet Varlet is a technology company focused on creating innovative solutions for the gaming community, with special emphasis on FiveM server management and Discord bot development. ### Resources - [GitHub Repository](https://github.com/jjuniornoc-rgb/varlet-fivem-api) - [NPM Package](https://www.npmjs.com/package/varlet-fivem-api) - [Documentation](https://docs.varlet.com)