Skip to main content

Module env

Module env 

Source
Expand description

Typesafe environment variable access for FORGE functions.

This module provides a centralized, testable abstraction for reading environment variables. Instead of scattering std::env::var() calls throughout your functions, use ctx.env() methods which:

  • Provide type-safe parsing with clear error messages
  • Are easily mockable in tests via test context builders
  • Record which variables were accessed (for debugging)

§Example

#[forge::mutation]
async fn call_stripe(ctx: &MutationContext, input: ChargeInput) -> Result<Charge> {
    // Get required env var (returns error if missing)
    let api_key = ctx.env_require("STRIPE_API_KEY")?;

    // Get optional env var with default
    let timeout = ctx.env_or("STRIPE_TIMEOUT", "30");

    // Get and parse to specific type
    let max_retries: u32 = ctx.env_parse("STRIPE_MAX_RETRIES")?;

    // Make HTTP call
    let response = ctx.http().post("https://api.stripe.com/...").send().await?;

    // ...
}

§Testing

#[test]
fn test_stripe_mutation() {
    let ctx = TestMutationContext::builder()
        .with_env("STRIPE_API_KEY", "sk_test_xxx")
        .with_env("STRIPE_TIMEOUT", "60")
        .mock_http_json("https://api.stripe.com/*", json!({"id": "ch_123"}))
        .build();

    // Function will use mocked env vars and HTTP responses
}

Structs§

MockEnvProvider
Mock environment provider for testing.
RealEnvProvider
Production environment provider that reads from std::env.

Traits§

EnvAccess
Extension methods for environment variable access on contexts.
EnvProvider
Trait for environment variable access.