UNPKG

cube-ms

Version:

Production-ready microservice framework with health monitoring, validation, error handling, and Docker Swarm support

156 lines (135 loc) • 5.15 kB
#!/usr/bin/env node /** * Environment Validation Script * Validates that all required environment variables are set */ import { fileURLToPath } from 'url'; import { dirname, join } from 'path'; import fs from 'fs-extra'; import chalk from 'chalk'; import dotenv from 'dotenv'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); const projectRoot = join(__dirname, '..'); /** * Load environment variables */ function loadEnvironment() { const envPath = join(projectRoot, '.env'); if (fs.existsSync(envPath)) { dotenv.config({ path: envPath }); return true; } return false; } /** * Validate environment configuration */ function validateEnvironment() { console.log(chalk.blue('šŸ” Validating environment configuration...')); const hasEnvFile = loadEnvironment(); let isValid = true; const issues = []; const warnings = []; // Check for .env file if (!hasEnvFile) { issues.push('Missing .env file'); console.log(chalk.yellow('āš ļø .env file not found')); console.log(chalk.gray(' Create .env file from .env.example template')); } else { console.log(chalk.green('āœ… .env file found')); } // Required environment variables for API template const requiredVars = [ { name: 'NODE_ENV', default: 'development' }, { name: 'PORT', default: '3000' }, { name: 'MONGODB_URL', default: 'mongodb://localhost:27017/app' }, { name: 'SERVICE_NAME', default: 'api-service' }, ]; // Optional but recommended variables const recommendedVars = [ { name: 'JWT_SECRET', description: 'Required for authentication' }, { name: 'API_KEY', description: 'For API authentication' }, { name: 'CCN_LOGGING_ENABLED', description: 'Enable CCN logging' }, { name: 'SECURITY_ENABLED', description: 'Enable security features' }, { name: 'RATE_LIMIT_ENABLED', description: 'Enable rate limiting' }, ]; // Check required variables console.log(chalk.blue('\nšŸ“‹ Required Environment Variables:')); requiredVars.forEach(({ name, default: defaultValue }) => { if (!process.env[name]) { if (hasEnvFile) { issues.push(`Missing required variable: ${name}`); console.log(chalk.red(`āŒ ${name} - Missing (default: ${defaultValue})`)); } else { warnings.push(`${name} will use default: ${defaultValue}`); console.log(chalk.yellow(`āš ļø ${name} - Using default: ${defaultValue}`)); } } else { console.log(chalk.green(`āœ… ${name} - Set`)); } }); // Check recommended variables console.log(chalk.blue('\nšŸ”§ Recommended Environment Variables:')); recommendedVars.forEach(({ name, description }) => { if (!process.env[name]) { warnings.push(`Consider setting ${name}: ${description}`); console.log(chalk.yellow(`āš ļø ${name} - Not set (${description})`)); } else { console.log(chalk.green(`āœ… ${name} - Set`)); } }); // Database connection validation console.log(chalk.blue('\nšŸ—„ļø Database Configuration:')); const mongoUrl = process.env.MONGODB_URL || 'mongodb://localhost:27017/app'; console.log(chalk.gray(` MongoDB URL: ${mongoUrl.replace(/\/\/[^:]+:[^@]+@/, '//***:***@')}`)); // Node.js version check console.log(chalk.blue('\n🟢 Node.js Version:')); const nodeVersion = process.version; const majorVersion = parseInt(nodeVersion.slice(1).split('.')[0]); if (majorVersion >= 18) { console.log(chalk.green(`āœ… Node.js ${nodeVersion} (supported)`)); } else { issues.push(`Node.js version ${nodeVersion} is below minimum required (18.0.0)`); console.log(chalk.red(`āŒ Node.js ${nodeVersion} (minimum: 18.0.0)`)); isValid = false; } // Summary console.log(chalk.blue('\nšŸ“Š Validation Summary:')); if (issues.length > 0) { console.log(chalk.red(`āŒ ${issues.length} issue(s) found:`)); issues.forEach(issue => console.log(chalk.red(` • ${issue}`))); isValid = false; } if (warnings.length > 0) { console.log(chalk.yellow(`āš ļø ${warnings.length} warning(s):`)); warnings.forEach(warning => console.log(chalk.yellow(` • ${warning}`))); } if (isValid && issues.length === 0) { console.log(chalk.green('āœ… Environment validation passed')); } else { console.log(chalk.red('āŒ Environment validation failed')); } // Next steps if (!hasEnvFile || issues.length > 0) { console.log(chalk.cyan('\nšŸ“‹ Next steps:')); if (!hasEnvFile) { console.log(chalk.white(' 1. Copy .env.example to .env')); console.log(chalk.white(' 2. Update values in .env file')); } console.log(chalk.white(' 3. Set up CCN registry: npm run setup-npmrc')); console.log(chalk.white(' 4. Run validation again: npm run validate-env')); } return isValid; } // Main execution if (import.meta.url === `file://${process.argv[1]}`) { try { const isValid = validateEnvironment(); process.exit(isValid ? 0 : 1); } catch (error) { console.error(chalk.red(`āŒ Environment validation failed: ${error.message}`)); process.exit(1); } } export { validateEnvironment };