### ApexRP Installation and Configuration Source: https://github.com/rahulomegalul/apexrp/blob/main/resources/apex-core/docs/getting-started.md Instructions for installing additional ApexRP resources and configuring server settings for different player counts. ```APIDOC ## ApexRP Resource Installation ### Description Install additional ApexRP resources by ensuring them in your `server.cfg` file. The load order is important. ### Resources - **apex-admin**: Admin panel and moderation tools - **apex-inventory**: Advanced inventory system - **apex-multichar**: Multi-character selection - **apex-appearance**: Character customization ### Installation Example ```bash # In server.cfg (load order matters!) ensure apex-core ensure apex-admin ensure apex-inventory ensure apex-multichar ``` ## Performance Tuning ### Description Adjust server configuration variables (`set`) to optimize performance based on the expected player count. ### Configuration for 100-300 Players ```bash set apex_db_pool_size "10" set apex_cache_mode "memory" ``` ### Configuration for 300-500 Players ```bash set apex_db_pool_size "20" set apex_cache_mode "redis" ``` ### Configuration for 500+ Players ```bash set apex_db_pool_size "30" set apex_cache_mode "redis" # + Use PgBouncer # + Use PostgreSQL read replicas # + Load balance FiveM instances ``` ``` -------------------------------- ### Create a New ApexRP Resource (Bash, Lua) Source: https://github.com/rahulomegalul/apexrp/blob/main/resources/apex-core/docs/getting-started.md Guides on creating a new resource for ApexRP. It includes bash commands to set up the resource directory and provides example `fxmanifest.lua`, `server.lua`, and `client.lua` files demonstrating dependency on `apex-core` and basic RPC interaction. ```bash cd resources/ mkdir my-resource cd my-resource ``` ```lua fx_version 'cerulean' game 'gta5' author 'Your Name' description 'My first ApexRP resource' version '1.0.0' -- Depend on apex-core dependency 'apex-core' client_scripts { 'client.lua' } server_scripts { 'server.lua' } ``` ```lua -- Use apex-core exports local player = exports['apex-core']:findPlayerByLicense('license:abc123') print('Player:', json.encode(player)) -- Register RPC handler exports['apex-core']:registerRPC('my-resource:test', nil, function(params, context) print('RPC called by player:', context.source) return { success = true, message = 'Hello from my-resource!' } end) ``` ```lua RegisterCommand('testRPC', function() local result = exports['apex-core']:callRPC('my-resource:test', {}) print('RPC result:', json.encode(result)) end, false) ``` -------------------------------- ### Quick Start: Set Up ApexRP Server Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/index.md This snippet guides users through cloning the ApexRP repository, installing dependencies, setting up the PostgreSQL database, building the framework, and starting the FiveM server. It requires Git, Bun, and PostgreSQL to be installed. ```bash git clone https://github.com/RahulOmegalul/ApexRP cd ApexRP cd resources/apex-core bun install createdb apex_rp echo 'set apex_db_url "postgres://localhost:5432/apex_rp"' >> server.cfg bun run build cd ../.. ./FXServer.exe +exec server.cfg ``` -------------------------------- ### System Stats Query Examples (SQL) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/guides/database.md Provides example SQL queries for the 'system_stats' table. Shows how to view all statistics and retrieve the value for a specific key. ```sql -- View all stats SELECT * FROM system_stats; -- Get specific stat SELECT value FROM system_stats WHERE key = 'total_players'; ``` -------------------------------- ### System Migration Logs Query Examples (SQL) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/guides/database.md Provides example SQL queries for the 'system_migration_logs' table. Demonstrates viewing all migrations, checking for failures, and calculating average migration times. ```sql -- View all migrations SELECT * FROM system_migration_logs ORDER BY applied_at DESC; -- Check for failed migrations SELECT * FROM system_migration_logs WHERE status = 'failure'; -- Calculate average migration time SELECT AVG(duration) as avg_duration_ms FROM system_migration_logs; ``` -------------------------------- ### Install and Manage PostgreSQL (Linux) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/guides/database.md Installs PostgreSQL and its contrib modules on Ubuntu/Debian systems, starts the service, enables it to run on boot, and provides commands to verify installation and check service status. ```bash # Update package list sudo apt update # Install PostgreSQL sudo apt install postgresql postgresql-contrib # Start and enable service sudo systemctl start postgresql sudo systemctl enable postgresql # Verify installation psql --version # Check service status sudo systemctl status postgresql ``` -------------------------------- ### Create a New Resource with ApexRP Core Dependencies (Lua) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/getting-started.md Demonstrates the setup for a new FiveM resource that depends on ApexRP core. This includes creating the `fxmanifest.lua` file to declare dependencies and specify client/server scripts, and providing basic `server.lua` and `client.lua` examples that utilize ApexRP core exports for finding players, registering RPC handlers, and calling RPC methods. ```lua fx_version 'cerulean' game 'gta5' author 'Your Name' description 'My first ApexRP resource' version '1.0.0' -- Depend on apex-core dependency 'apex-core' client_scripts { 'client.lua' } server_scripts { 'server.lua' } ``` ```lua -- Use apex-core exports local player = exports['apex-core']:findPlayerByLicense('license:abc123') print('Player:', json.encode(player)) -- Register RPC handler exports['apex-core']:registerRPC('my-resource:test', nil, function(params, context) print('RPC called by player:', context.source) return { success = true, message = 'Hello from my-resource!' } end) ``` ```lua RegisterCommand('testRPC', function() local result = exports['apex-core']:callRPC('my-resource:test', {}) print('RPC result:', json.encode(result)) end, false) ``` -------------------------------- ### Install Dependencies with Bun (Bash) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/getting-started.md Installs project dependencies using the Bun package manager. It navigates to the apex-core directory and runs 'bun install'. Includes troubleshooting tips to use 'npm install' if Bun fails. ```bash cd apex-core bun install ``` -------------------------------- ### Example Development Setup (Minimal) Source: https://github.com/rahulomegalul/apexrp/blob/main/resources/apex-core/docs/CONFIGURATION.md A minimal configuration example for a development environment. It sets the database URL and relies on default values for other settings like cache mode, log level, RPC timeout, and HTTP server configuration. ```bash # Database set apex_db_url "postgres://dev:dev@localhost:5432/apex_rp_dev" # Everything else uses defaults # Cache: memory # Log level: info # RPC timeout: 5000ms # HTTP: localhost:9090 (no auth) ``` -------------------------------- ### Item Query Examples (SQL) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/guides/database.md Provides example SQL queries for interacting with the 'items' table. Demonstrates how to find items by name, filter for usable items, and retrieve heavy items. ```sql -- Find item by name SELECT * FROM items WHERE name = 'water_bottle'; -- Find all usable items SELECT * FROM items WHERE usable = true; -- Find heavy items SELECT * FROM items WHERE weight > 1000 ORDER BY weight DESC; ``` -------------------------------- ### System Metric Snapshots Query Examples (SQL) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/guides/database.md Provides example SQL queries for the 'system_metric_snapshots' table. Demonstrates retrieving recent metrics and aggregating data over time, such as hourly RPC calls. ```sql -- Get metrics for last hour SELECT * FROM system_metric_snapshots WHERE timestamp > NOW() - INTERVAL '1 hour' ORDER BY timestamp DESC; -- Aggregate RPC calls per hour SELECT DATE_TRUNC('hour', timestamp) as hour, SUM(value) as total_calls FROM system_metric_snapshots WHERE metric = 'rpc_calls' GROUP BY hour ORDER BY hour DESC; ``` -------------------------------- ### Starting the FiveM Server with ApexRP Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/getting-started.md The command to initiate the FiveM server, loading the ApexRP resources and configuration. It navigates to the server directory and executes the server binary, applying the server.cfg file. ```bash cd /path/to/fivem-server/ ./FXServer +exec server.cfg ``` -------------------------------- ### Install and Manage PostgreSQL (macOS) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/guides/database.md Installs PostgreSQL using Homebrew on macOS, starts the service, and verifies the installation by checking the psql version. ```bash # Install via Homebrew brew install postgresql # Start service brew services start postgresql # Verify installation psql --version ``` -------------------------------- ### Example Testing/Debug Setup Source: https://github.com/rahulomegalul/apexrp/blob/main/resources/apex-core/docs/CONFIGURATION.md An example configuration for a testing or debugging environment. It primarily sets the database URL for the test database. ```bash # Database set apex_db_url "postgres://test:test@localhost:5432/apex_rp_test" ``` -------------------------------- ### Install ApexRP Resources Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/getting-started.md This snippet shows how to load additional ApexRP resources like admin tools, inventory, and character customization. The order in which these are loaded in `server.cfg` is crucial for proper functionality. ```bash # In server.cfg (load order matters!) ensure apex-core ensure apex-admin ensure apex-inventory ensure apex-multichar ``` -------------------------------- ### Inventory Query Examples (SQL) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/guides/database.md Provides example SQL queries for the 'inventory' table. Shows how to retrieve all items for a player, calculate total player weight, and find players possessing a specific item. ```sql -- Find all items for a player SELECT inv.*, items.label, items.weight FROM inventory inv JOIN items ON inv.item_id = items.id WHERE inv.owner = 'player:1' ORDER BY inv.slot; -- Find total weight for a player SELECT SUM(items.weight * inv.quantity) as total_weight FROM inventory inv JOIN items ON inv.item_id = items.id WHERE inv.owner = 'player:1'; -- Find all players with a specific item SELECT DISTINCT owner FROM inventory WHERE item_id = (SELECT id FROM items WHERE name = 'water_bottle'); ``` -------------------------------- ### Installation Guide Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/guides/architecture.md Step-by-step instructions for installing and setting up the ApexRP project. ```APIDOC ## Installation ```bash # 1. Clone cd resources/ git clone apex-core # 2. Install dependencies cd apex-core bun install # 3. Build bun run build # 4. Configure # server.cfg: set apex_db_url "postgres://user:pass@localhost:5432/apex_rp" # 5. Load resource (MUST load early) ensure apex-core ``` ``` -------------------------------- ### ApexRP Quick Reference Commands Source: https://github.com/rahulomegalul/apexrp/blob/main/resources/apex-core/docs/getting-started.md A collection of essential commands for building, testing, database management, and in-game operations. ```APIDOC ## Essential Commands ### Build and Development - **Build**: `bun run build` - **Watch mode (development)**: `bun run watch` ### Database Management - **Generate migration**: `bun run db:generate` - **Apply migrations**: `bun run db:migrate` - **Open Drizzle Studio GUI**: `bun run db:studio` ### Testing - **Run tests**: `bun test` ## In-Game Commands ### Description Commands to execute within the game for health checks, metrics, and database migration rollback. - **Health check**: `apex:health` - **Performance metrics**: `apex:metrics` - **Rollback migration (with backup name)**: `apex:db:rollback` ``` -------------------------------- ### Example Production Setup (Single Server) Source: https://github.com/rahulomegalul/apexrp/blob/main/resources/apex-core/docs/CONFIGURATION.md An example configuration for a production environment on a single server. It specifies database credentials, cache mode, log level, RPC timeout, and secures the HTTP monitoring endpoints with an API key and rate limiting. The IP salt must be changed for security. ```bash # Database set apex_db_url "postgres://apexrp:SECURE_PASSWORD@db.internal:5432/apex_rp_prod" # Cache set apex_cache_mode "memory" # Logging set apex_log_level "warn" # RPC set apex_rpc_timeout "10000" # HTTP Monitoring set apex_http_port "9090" set apex_http_bind "127.0.0.1" set apex_http_api_key "SECURE_RANDOM_KEY_HERE" set apex_http_rate_limit "30" # Security set apex_security_ip_salt "SECURE_RANDOM_SALT_HERE" ``` -------------------------------- ### ApexRP Player Table Example Queries (SQL) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/guides/database.md Provides example SQL queries for interacting with the 'players' table in ApexRP. These examples demonstrate how to find players by their license, Discord ID, and retrieve recently active players. ```sql -- Find player by license SELECT * FROM players WHERE license = 'license:abc123'; -- Find players by Discord SELECT * FROM players WHERE discord = 'discord:123456789012345678'; -- Find recently active players SELECT * FROM players WHERE last_seen > NOW() - INTERVAL '7 days'; ``` -------------------------------- ### Install ApexRP Resources Source: https://github.com/rahulomegalul/apexrp/blob/main/resources/apex-core/docs/getting-started.md This snippet shows how to load additional ApexRP resources by ensuring they are included in the server.cfg file. The order of these 'ensure' commands is critical for proper resource loading. ```bash # In server.cfg (load order matters!) ensure apex-core ensure apex-admin ensure apex-inventory ensure apex-multichar ensure apex-appearance ``` -------------------------------- ### Example Production Setup (Multi-Server with Redis) Source: https://github.com/rahulomegalul/apexrp/blob/main/resources/apex-core/docs/CONFIGURATION.md A configuration example for a production environment using multiple servers with Redis for caching. It includes database connection details, Redis configuration, logging level, RPC timeout, and secured HTTP monitoring. The API key and IP salt should be strong and unique. ```bash # Database set apex_db_url "postgres://apexrp:SECURE_PASSWORD@db.internal:5432/apex_rp_prod" # Cache set apex_cache_mode "redis" set apex_redis_host "redis.internal" set apex_redis_port "6379" set apex_redis_password "REDIS_PASSWORD_HERE" # Logging set apex_log_level "info" # RPC set apex_rpc_timeout "15000" # HTTP Monitoring set apex_http_port "9090" set apex_http_bind "0.0.0.0" set apex_http_api_key "SECURE_RANDOM_KEY_HERE" set apex_http_rate_limit "100" # Security set apex_security_ip_salt "SECURE_RANDOM_SALT_HERE" ``` -------------------------------- ### Install Redis on Windows via WSL Source: https://github.com/rahulomegalul/apexrp/blob/main/resources/apex-core/docs/caching-guide.md This guide installs Redis on Windows using the Windows Subsystem for Linux (WSL). It first installs the Ubuntu distribution for WSL and then proceeds with the standard Ubuntu/Debian Redis installation steps within the WSL environment. After installation, Redis is started in daemon mode. ```bash # Install WSL Ubuntu wsl --install -d Ubuntu # Inside WSL sudo apt update sudo apt install redis-server redis-server --daemonize yes ``` -------------------------------- ### PostgreSQL Connection String Formats (Bash) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/getting-started.md Provides examples of PostgreSQL connection strings used by apex-core, illustrating formats for local development, custom users, remote databases, and secure SSL connections. It also includes security recommendations for passwords and user privileges. ```bash # Local development (default) postgres://postgres:password@localhost:5432/apex_rp # Custom user postgres://apex_user:SecurePass123@localhost:5432/apex_rp # Remote database postgres://apex_user:password@192.168.1.100:5432/apex_rp # With SSL (production) postgres://apex_user:password@db.example.com:5432/apex_rp?sslmode=require ``` -------------------------------- ### Expected ApexRP First Start Console Output Source: https://github.com/rahulomegalul/apexrp/blob/main/resources/apex-core/docs/getting-started.md Illustrates the typical console messages displayed when the ApexRP server starts for the first time, including resource loading, database connection, and migration status. ```log [apex-core] Resource loaded successfully [apex-core] Initializing database connection... [apex-core] Database connected: postgres://apex_user@localhost:5432/apex_rp [apex-core] Running migrations... [apex-core] Applied migration: 0001_create_players_table (23ms) [apex-core] Applied migration: 0002_create_characters_table (18ms) [apex-core] Applied migration: 0003_create_vehicles_table (15ms) [apex-core] Applied migration: 0004_create_items_inventory (21ms) [apex-core] Applied migration: 0005_create_system_tables (12ms) [apex-core] Migrations completed successfully (89ms) [apex-core] RPC server initialized [apex-core] HTTP server listening on http://localhost:9090 [apex-core] apex-core v1.0.0 started successfully ✓ ``` -------------------------------- ### Install and Run Redis with Docker (Bash) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/guides/caching.md Installs and runs a Redis instance using Docker. Includes options for development with persistence and production with password authentication. Also provides a Docker Compose configuration for a more robust setup. ```bash # Start Redis with persistence docker run -d \ --name apex-redis \ -p 6379:6379 \ -v apex-redis-data:/data \ redis:latest redis-server --appendonly yes # Verify connection docker exec apex-redis redis-cli ping # Should output: PONG ``` ```bash # Generate secure password REDIS_PASSWORD=$(openssl rand -base64 32) # Start Redis with authentication docker run -d \ --name apex-redis \ --restart unless-stopped \ -p 6379:6379 \ -v apex-redis-data:/data \ redis:latest redis-server \ --appendonly yes \ --requirepass "$REDIS_PASSWORD" # Test authentication docker exec apex-redis redis-cli -a "$REDIS_PASSWORD" ping ``` ```yaml version: '3.8' services: redis: image: redis:latest container_name: apex-redis restart: unless-stopped ports: - "6379:6379" volumes: - apex-redis-data:/data command: redis-server --appendonly yes --requirepass ${REDIS_PASSWORD} healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 10s timeout: 3s retries: 3 volumes: apex-redis-data: ``` -------------------------------- ### Explore ApexRP Core API and Exports (TypeScript) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/getting-started.md Illustrates how to interact with the ApexRP core API and its exports within a TypeScript environment. It shows examples of importing database modules, schema definitions, repository patterns, and making RPC calls. This snippet is crucial for understanding how to build custom resources that leverage the core framework. ```typescript // Database queries import { db, schema, PlayerRepository } from '@apexrp-js/core/server'; // RPC calls import { RPC } from '@apexrp-js/core/client'; // State management import { PlayerState, VehicleState, UIState } from '@apexrp-js/core/client'; ``` -------------------------------- ### ApexRP Configuration Summary Source: https://github.com/rahulomegalul/apexrp/blob/main/resources/apex-core/docs/getting-started.md A summary of available configuration variables (convars) with their default values and descriptions. ```APIDOC ## Configuration Summary ### Description This table outlines the key configuration variables (convars) used by ApexRP, including their default values and purpose. | Convar | Default | Description | |---|---|---| | `apex_db_url` | `postgres://localhost:5432/apex_rp` | PostgreSQL connection string | | `apex_db_pool_size` | `10` | Connection pool size | | `apex_cache_mode` | `memory` | Cache mode (memory, redis, hybrid, none) | | `apex_redis_host` | `localhost` | Redis host (if using Redis) | | `apex_redis_port` | `6379` | Redis port | | `apex_log_level` | `info` | Log level (debug, info, warn, error) | | `apex_rpc_timeout` | `10000` | RPC timeout (milliseconds) | ``` -------------------------------- ### Redis Configuration for ApexRP Caching Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/getting-started.md Optional configuration for enabling Redis caching in ApexRP. This is recommended for larger player counts or multi-instance setups. Requires Redis to be installed and running separately. ```bash # Configure in server.cfg set apex_cache_mode "redis" set apex_redis_host "localhost" set apex_redis_port "6379" # set apex_redis_password "your_redis_password" # If Redis has auth enabled ``` -------------------------------- ### Verify PostgreSQL Installation (Windows) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/guides/database.md Checks if the PostgreSQL client is installed and accessible by verifying its version. This command is run in the Windows Command Prompt. ```cmd psql --version # Should show: psql (PostgreSQL) 14.x or higher ``` -------------------------------- ### Project Setup (Bash) Source: https://github.com/rahulomegalul/apexrp/blob/main/resources/apex-core/docs/tutorials/04-state-management.md Commands to create a new resource directory structure for the Apex HUD system. It includes creating the main directory and organizing client and shared subdirectories. ```bash cd resources/ mkdir apex-hud cd apex-hud # Create directory structure mkdir -p src/{client,shared} ``` -------------------------------- ### Install PgBouncer Connection Pooler Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/guides/database.md Provides the command to install PgBouncer, a lightweight connection pooler for PostgreSQL, on a Debian/Ubuntu system. Connection pooling is recommended for high concurrency environments. ```bash sudo apt install pgbouncer ``` -------------------------------- ### Project Directory Structure Setup (Bash) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/tutorials/database-integration.md This sequence of bash commands sets up the necessary directory structure for the new rental system resource. It includes creating the main resource folder and organizing subdirectories for server, client, and shared code, including database schema and repositories. ```bash cd resources/ mkdir apex-rentals cd apex-rentals # Create directory structure mkdir -p src/{server/{database/{schema,repositories},rpc},client,shared} ``` -------------------------------- ### ApexRP Character Table Example Queries (SQL) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/guides/database.md Provides example SQL queries for the 'characters' table. These queries show how to retrieve all characters for a specific player, find a character by their unique identifier, and identify the wealthiest characters. ```sql -- Find all characters for a player SELECT * FROM characters WHERE player_id = 1 AND is_deleted = false; -- Find character by identifier SELECT * FROM characters WHERE identifier = 'char:1:license:abc123'; -- Find richest characters SELECT first_name, last_name, (cash + bank) as total_money FROM characters WHERE is_deleted = false ORDER BY total_money DESC LIMIT 10; ``` -------------------------------- ### Build and Server Configuration Source: https://github.com/rahulomegalul/apexrp/blob/main/resources/apex-core/docs/tutorials/04-state-management.md Commands for building the resource and configuring the server to run it. Includes instructions for building the client script, ensuring necessary resources ('apex-core', 'apex-hud'), and restarting the server. ```bash # Build the resource bun run build # Output: dist/client.js ✅ # Add to server.cfg ensure apex-core ensure apex-hud # Restart server and test in-game: ``` -------------------------------- ### ApexRP Vehicle Table Example Queries (SQL) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/guides/database.md Provides example SQL queries for the 'vehicles' table. These demonstrate how to find all vehicles belonging to a specific character, search for a vehicle by its license plate, and list all vehicles currently in a 'garaged' state. ```sql -- Find all vehicles for a character SELECT * FROM vehicles WHERE character_id = 1; -- Find vehicle by plate SELECT * FROM vehicles WHERE plate = 'ABC 123'; -- Find all garaged vehicles SELECT * FROM vehicles WHERE state = 'garaged'; ``` -------------------------------- ### Database Migration Commands (Bash & SQL) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/tutorials/database-integration.md Provides instructions for applying database migrations for the rental system. Includes automatic, manual (using bun), and direct SQL methods. Also shows SQL commands to verify the migration by checking table and index existence. ```bash # Apply migration manually bun run db:migrate ``` ```bash psql -U apex_user -d apex_rp < migrations/0001_create_rentals.sql ``` ```sql -- Check tables exist \dt rentals \dt rental_history -- Check indexes \di rentals* ``` -------------------------------- ### Create PostgreSQL Database and User (SQL/Bash) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/getting-started.md Demonstrates how to set up a PostgreSQL database named 'apex_rp' and a dedicated user 'apex_user' with a password using the psql command-line tool. It grants all necessary privileges to the new user for the database. ```bash # Connect to PostgreSQL psql -U postgres # Create database CREATE DATABASE apex_rp; # Create user (recommended for security) CREATE USER apex_user WITH ENCRYPTED PASSWORD 'your_secure_password'; # Grant privileges GRANT ALL PRIVILEGES ON DATABASE apex_rp TO apex_user; # Exit \q ``` -------------------------------- ### Apply Database Migrations Manually (Bash) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/guides/database.md This command manually applies all pending database migrations using Bun. It's typically used for testing or in scenarios where automatic migration on server start is not desired or fails. ```bash bun run db:migrate ``` -------------------------------- ### Build and Server Configuration (Bash) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/tutorials/database-integration.md Commands for building the ApexRP rental resource and configuring the server to run it. Includes the build command using 'bun run build' and instructions to add the resource to 'server.cfg'. ```bash # Build the resource bun run build # Output: dist/server.js dist/client.js ``` ```bash ensure apex-core ensure apex-rentals ``` -------------------------------- ### Check PostgreSQL Status and Connection (Bash) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/guides/database.md This bash snippet provides commands to check the status of the PostgreSQL service, start it if necessary, verify it's listening on the correct port, and test the connection. It helps diagnose 'Connection refused' errors. ```bash # Check PostgreSQL status # Linux: sudo systemctl status postgresql sudo systemctl start postgresql # Windows: Services → postgresql-x64-14 → Start # Check if listening on port netstat -an | grep 5432 # Should show: LISTEN on 0.0.0.0:5432 or 127.0.0.1:5432 # Test connection psql -U apex_user -d apex_rp -h localhost -p 5432 ``` -------------------------------- ### Manual Redis Installation (Bash) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/guides/caching.md Provides instructions for manually installing Redis on Ubuntu/Debian systems and Windows via WSL. Includes steps for configuration, persistence, and restarting the service. ```bash # Install Redis sudo apt update sudo apt install redis-server # Configure persistence sudo nano /etc/redis/redis.conf # Set: appendonly yes # Set: requirepass your-secure-password # Restart service sudo systemctl restart redis-server sudo systemctl enable redis-server # Verify redis-cli ping ``` ```bash # Install WSL Ubuntu wsl --install -d Ubuntu # Inside WSL sudo apt update sudo apt install redis-server redis-server --daemonize yes ``` -------------------------------- ### Set Up Server Entry Point and Periodic Tasks (TypeScript) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/tutorials/database-integration.md Initializes the server by importing RPC handlers and setting up a recurring task to expire overdue rentals. This ensures the rental system is active and maintained. ```typescript import './rpc/rental.rpc'; import { rentalRepository } from './database/repositories/rental.repository'; // Periodic task: Expire overdue rentals every 5 minutes setInterval(async () => { try { const expired = await rentalRepository.expireOverdueRentals(); if (expired > 0) { console.log(`[apex-rentals] Expired ${expired} overdue rentals`); } } catch (error) { console.error('[apex-rentals] Failed to expire rentals:', error); } }, 5 * 60 * 1000); console.log('[apex-rentals] Server-side loaded'); ``` -------------------------------- ### Configure Prometheus Monitoring for ApexRP Core (YAML) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/getting-started.md Shows how to configure Prometheus to scrape metrics from ApexRP core. This involves defining a `scrape_configs` section in `prometheus.yml` to target the ApexRP core job, typically running on `localhost:9090`. This setup is essential for production monitoring. ```yaml # prometheus.yml scrape_configs: - job_name: 'apex-core' static_configs: - targets: ['localhost:9090'] ``` -------------------------------- ### Adjust Log Verbosity Levels (Bash) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/getting-started.md Explains how to control the verbosity of log output using the `apex_log_level` setting. Examples are provided for setting the level to 'debug' for more detailed output during development and 'warn' for a less verbose output in production environments. A resource restart is required to apply these changes. ```bash # More verbose (debugging) set apex_log_level "debug" # Less verbose (production) set apex_log_level "warn" # Restart resource to apply restart apex-core ``` -------------------------------- ### Essential PostgreSQL and Migration Commands Source: https://github.com/rahulomegalul/apexrp/blob/main/resources/apex-core/docs/database-guide.md A quick reference for common command-line operations related to PostgreSQL and database migrations. Includes connecting to the database, generating/applying migrations, opening Drizzle Studio, backing up, restoring, and checking database size. ```bash # Database connection psql -U apex_user -d apex_rp # Generate migration bun run db:generate # Apply migrations manually bun run db:migrate # Open Drizzle Studio (GUI) bun run db:studio # Backup database pg_dump -U apex_user -d apex_rp -F c -f backup.dump # Restore database pg_restore -U apex_user -d apex_rp backup.dump # Check database size psql -U apex_user -d apex_rp -c "SELECT pg_size_pretty(pg_database_size('apex_rp'));" ``` -------------------------------- ### Run PostgreSQL with Docker Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/guides/database.md Starts a PostgreSQL 14 Docker container named 'apex-postgres', sets the password to 'postgres', names the database 'apex_rp', maps port 5432, and mounts a volume for data persistence. It also includes commands to verify the container is running and connect to the database. ```bash # Run PostgreSQL container docker run -d \ --name apex-postgres \ -e POSTGRES_PASSWORD=postgres \ -e POSTGRES_DB=apex_rp \ -p 5432:5432 \ -v apex_data:/var/lib/postgresql/data \ postgres:14 # Verify container is running docker ps | grep apex-postgres # Connect to database docker exec -it apex-postgres psql -U postgres -d apex_rp ``` -------------------------------- ### Reactive Store Usage (TypeScript) Source: https://github.com/rahulomegalul/apexrp/blob/main/resources/apex-core/docs/tutorials/04-state-management.md Illustrates the recommended reactive store pattern using ApexRP's client state. It shows how to subscribe to state changes and initialize the store for automatic updates. ```typescript // Reactive store - automatic updates import { playerState } from '@apex-core/client'; playerState.subscribe((state) => { console.log(`Health: ${state.health}`); // ✅ Auto-runs on change }); // Store handles polling internally playerState.init(); ``` -------------------------------- ### Cloud Redis Setup (DigitalOcean CLI) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/guides/caching.md Illustrates creating a DigitalOcean Managed Redis database and retrieving its connection string using the doctl CLI. This is a managed Redis option for DigitalOcean users. ```bash # Create via doctl CLI doctl databases create apex-redis \ --engine redis \ --region nyc3 \ --size db-s-1vcpu-1gb # Get connection string doctl databases connection apex-redis ``` -------------------------------- ### Start NUI Development Server Source: https://github.com/rahulomegalul/apexrp/blob/main/CONTRIBUTING.md Installs dependencies and starts the development server for the React-based NUI interface. This allows for isolated UI component development and verification. ```bash cd web bun install bun run dev ``` -------------------------------- ### Using the Custom Job Store (TypeScript) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/tutorials/state-management.md Shows how to import and use the custom `jobStore`. It demonstrates clocking in and subscribing to state changes to log working status and earnings, illustrating practical application of the store. ```typescript // Usage import { jobStore } from './stores/jobStore'; // Clock in jobStore.clockIn(); // Track earnings jobStore.subscribe((state) => { if (state.onDuty) { console.log(`Working as ${state.currentJob}, earned $${state.earnings}`); } }); ``` -------------------------------- ### Troubleshoot Log File Creation Issues (Bash) Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/getting-started.md Guides users through diagnosing and resolving problems with log file creation. This includes checking directory write permissions for the 'logs/' folder, fixing permissions using `chmod` on Linux, verifying disk space with `df -h`, and cleaning old log files by removing outdated `.log` files. ```bash # Check directory permissions ls -la resources/apex-core/ # logs/ should be writable # Fix permissions (Linux) chmod 755 resources/apex-core/logs/ # Check disk space df -h # If disk full, clean old logs cd resources/apex-core/logs/ rm apex-core-2025-*.log # Delete old year's logs ``` -------------------------------- ### Install Vercel CLI and Login Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/DEPLOYMENT.md Commands to install the Vercel Command Line Interface globally using npm and then log in to your Vercel account. This is the first step for deploying with Vercel. ```bash npm i -g vercel vercel login ``` -------------------------------- ### ApexRP Development Commands Source: https://github.com/rahulomegalul/apexrp/blob/main/docs/getting-started.md A collection of essential commands for developing with ApexRP using Bun. This includes building the project, running in watch mode for development, managing database migrations, and running tests. ```bash # Build bun run build # Watch mode (development) bun run watch # Database migrations bun run db:generate # Generate migration bun run db:migrate # Apply migrations bun run db:studio # Open Drizzle Studio GUI # Tests bun test ``` -------------------------------- ### ApexRP HTTP Endpoints Source: https://github.com/rahulomegalul/apexrp/blob/main/resources/apex-core/docs/getting-started.md Exposes health and metrics information via HTTP endpoints. ```APIDOC ## HTTP Endpoints ### Description Access health and performance metrics data through the following HTTP endpoints. ### Health Check - **Endpoint**: `http://localhost:9090/health` - **Method**: GET - **Response**: JSON containing health status. ### Metrics - **Endpoint**: `http://localhost:9090/metrics` - **Method**: GET - **Response**: JSON containing performance metrics. ### Request Example (Health Check) ```json { "status": "ok" } ``` ### Response Example (Metrics) ```json { "cpu_usage": 0.15, "memory_usage": 0.30, "active_players": 150 } ``` ```