Skip to content

feat(runtime): generate environment configuration layer #15

Description

@dev-queiroz

Summary

Generate environment configuration module with Zod validation and typed access to environment variables.

Motivation

Real backends need environment-based configuration (database URL, port, secrets). Currently developers must write this manually. This feature generates a production-ready ConfigService with runtime validation using Zod.

Scope

In Scope

  • .env.example file with all required variables
  • src/config/ module with ConfigService
  • Zod schema validation at startup
  • Support for NODE_ENV (development/production/test)
  • DATABASE_URL validation
  • Port configuration (default 3000)
  • JWT_SECRET validation (if auth enabled)
  • Clear error messages if required vars missing

Out of Scope

  • Vault/secret management integration
  • Environment variable encryption
  • Configuration hot-reload

Acceptance Criteria

  • .env.example generated with all variables
  • src/config/config.service.ts generated
  • ConfigService is @Injectable()
  • Zod schema validates at app startup
  • Fails startup if required var missing
  • NODE_ENV supports development/production/test
  • DATABASE_URL validated as URL format
  • PORT can be configured via env (default 3000)
  • JWT_SECRET validated if auth feature enabled
  • Error messages are clear and actionable
  • ConfigService exported from app.module

Files to Create/Modify

  • packages/generators/src/nest/templates/config.service.template.ts (NEW)
  • packages/generators/src/nest/templates/.env.example (NEW)
  • packages/generators/src/nest/generator.ts (MODIFY)
  • tests/nest-config.test.mjs (NEW)

Example Output

// src/config/config.service.ts
import { z } from 'zod';

const EnvSchema = z.object({
  NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
  PORT: z.coerce.number().default(3000),
  DATABASE_URL: z.string().url(),
  JWT_SECRET: z.string().min(32),
});

@Injectable()
export class ConfigService {
  private config: z.infer<typeof EnvSchema>;

  constructor() {
    try {
      this.config = EnvSchema.parse(process.env);
    } catch (error) {
      throw new Error(`Invalid environment configuration: ${error.message}`);
    }
  }

  get port(): number {
    return this.config.PORT;
  }

  get database(): string {
    return this.config.DATABASE_URL;
  }
}

Test Strategy

  • Generate config module from contract
  • Test with missing required env vars (should throw)
  • Test with valid .env file (should succeed)
  • Verify ConfigService injectable in AppModule
  • Test config values accessible in services

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions