environment-validation

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Environment Validation Pattern

环境验证模式

This is a reference pattern. Learn from the approach, adapt to your context — don't copy verbatim.
Problem: Scripts fail halfway through due to missing environment variables, wasting time and leaving systems in inconsistent states.
Solution: Validate all required environment variables at the start, before any operations begin.

这是一个参考模式。请参考其思路,适配你的实际场景——请勿逐字复制。
问题:脚本因缺少环境变量在运行中途失败,既浪费时间,又会导致系统处于不一致状态。
解决方案:在执行任何操作之前,优先在启动阶段验证所有必填环境变量。

Pattern

模式

Validate Early: Check all required configuration before starting business logic.
typescript
// ✅ Preferred: Validate at entry point
function validateEnvironment() {
  const required = ['AWS_REGION', 'PROJECT_ID', 'ENVIRONMENT'];
  const missing = required.filter(key => !process.env[key]);
  
  if (missing.length > 0) {
    throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
  }
}

// At script/app entry point
validateEnvironment();
// Now proceed with business logic
Environment Manager Pattern (for complex projects):
typescript
// shared/env-loader.ts
export function loadAndValidateEnv() {
  const required = ['AWS_REGION', 'PROJECT_ID', 'ENVIRONMENT'];
  const missing = required.filter(key => !process.env[key]);
  
  if (missing.length > 0) {
    throw new Error(`Missing: ${missing.join(', ')}`);
  }
  
  return {
    awsRegion: process.env.AWS_REGION!,
    projectId: process.env.PROJECT_ID!,
    environment: process.env.ENVIRONMENT!
  };
}

// Usage in scripts/handlers
const config = loadAndValidateEnv();
// All env vars validated, proceed with business logic

尽早验证:在启动业务逻辑前检查所有必填配置。
typescript
// ✅ Preferred: Validate at entry point
function validateEnvironment() {
  const required = ['AWS_REGION', 'PROJECT_ID', 'ENVIRONMENT'];
  const missing = required.filter(key => !process.env[key]);
  
  if (missing.length > 0) {
    throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
  }
}

// At script/app entry point
validateEnvironment();
// Now proceed with business logic
环境管理器模式(适用于复杂项目):
typescript
// shared/env-loader.ts
export function loadAndValidateEnv() {
  const required = ['AWS_REGION', 'PROJECT_ID', 'ENVIRONMENT'];
  const missing = required.filter(key => !process.env[key]);
  
  if (missing.length > 0) {
    throw new Error(`Missing: ${missing.join(', ')}`);
  }
  
  return {
    awsRegion: process.env.AWS_REGION!,
    projectId: process.env.PROJECT_ID!,
    environment: process.env.ENVIRONMENT!
  };
}

// Usage in scripts/handlers
const config = loadAndValidateEnv();
// All env vars validated, proceed with business logic

Benefits

优势

  • Fail Fast: Catch configuration errors immediately
  • Clear Errors: Know exactly what's missing
  • Clean Code: Business logic not cluttered with validation
  • Consistent: Single validation point for entire application

  • 快速失败:第一时间捕获配置错误
  • 报错清晰:可精准定位缺失的配置项
  • 代码简洁:业务逻辑不会被验证代码冗余
  • 一致性强:整个应用共用同一个验证入口

When to Use

适用场景

  • Always: For deployment scripts, Lambda handlers, CLI tools
  • Entry Points: Validate at application/script start
  • Shared Config: Use environment manager for complex projects

  • 通用场景:适用于部署脚本、Lambda handler、CLI 工具
  • 入口校验:在应用/脚本的启动位置进行验证
  • 共享配置:复杂项目可使用环境管理器统一管理

Integration with CLI Architecture

与CLI架构的集成

The 3-Tier CLI Architecture includes an
EnvironmentManager
that implements this pattern:
typescript
// core/env-manager.ts
export class EnvironmentManager extends BaseManager {
  loadEnv(stage: string): Record<string, string> {
    this.log(`Loading environment for ${stage}`);
    
    // Validate required variables
    const required = ['AWS_REGION', 'PROJECT_ID'];
    const missing = required.filter(key => !process.env[key]);
    
    if (missing.length > 0) {
      throw new Error(`Missing: ${missing.join(', ')}`);
    }
    
    return process.env;
  }
}
This ensures all CLI commands validate environment before executing business logic.

三层CLI架构中包含了实现该模式的
EnvironmentManager
typescript
// core/env-manager.ts
export class EnvironmentManager extends BaseManager {
  loadEnv(stage: string): Record<string, string> {
    this.log(`Loading environment for ${stage}`);
    
    // Validate required variables
    const required = ['AWS_REGION', 'PROJECT_ID'];
    const missing = required.filter(key => !process.env[key]);
    
    if (missing.length > 0) {
      throw new Error(`Missing: ${missing.join(', ')}`);
    }
    
    return process.env;
  }
}
这可以确保所有CLI命令在执行业务逻辑前都已完成环境校验。

Related

相关内容

  • CLI Architecture - 3-Tier pattern includes EnvironmentManager
  • Configuration Management
  • Error Handling
  • Security Baseline

  • CLI架构 - 包含环境管理器的三层模式
  • 配置管理
  • 错误处理
  • 安全基线

Progressive Improvement

持续优化

If the developer corrects a behavior that this skill should have prevented, suggest a specific amendment to this skill to prevent the same correction in the future.
如果开发者修正了本方案本应避免的问题,请提出具体的修订建议,避免未来再出现同类问题。