cube-ms
Version:
Production-ready microservice framework with health monitoring, validation, error handling, and Docker Swarm support
156 lines (135 loc) ⢠5.15 kB
JavaScript
/**
* 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 };