glenv

glenv is a library for type-sfe environment variable access.

Types

Definition represents a single environment variable, from key to type.

pub type Definition =
  #(String, Type)

EnvError represents an error that can occur when loading the environment.

pub type EnvError {
  MissingKeyError(key: String)
  InvalidEnvValueError(key: String, expected: Type)
  DefinitionMismatchError(errors: List(dynamic.DecodeError))
}

Constructors

  • MissingKeyError(key: String)

    The key was not found in the environment.

  • InvalidEnvValueError(key: String, expected: Type)

    The key was found in the environment but the value was not of the expected type.

  • DefinitionMismatchError(errors: List(dynamic.DecodeError))

    The key was found in the environment of the correct type, but the provided definition did not match.

Type represents the type of an environment variable. This dictates how the environment variable is parsed.

pub type Type {
  Bool
  Float
  Int
  String
}

Constructors

  • Bool

    Boolean type, represented by any casing of “true”, “yes”, or “1”.

  • Float

    Float type, represented by values like “1.0” or “1.000”.

  • Int

    Integer type, represented by values like “1” or “100”.

  • String

    String type, represented by any value.

Functions

pub fn load(
  decoder: Decoder(a),
  definitions: List(#(String, Type)),
) -> Result(a, EnvError)

Load parses the environment variables and returns a Result containing the environment. Takes a decoder from the gleam/decode library and a list of definitions.

Examples

type Env {
  Env(hello: String, foo: Float, count: Int, is_on: Bool)
}

let definitions = [
  #("HELLO", glenv.String),
  #("FOO", glenv.Float),
  #("COUNT", glenv.Int),
  #("IS_ON", glenv.Bool),
]

let decoder =
  decode.into({
    use hello <- decode.parameter
    use foo <- decode.parameter
    use count <- decode.parameter
    use is_on <- decode.parameter

    Env(hello: hello, foo: foo, count: count, is_on: is_on)
  })
  |> decode.field("HELLO", decode.string)
  |> decode.field("FOO", decode.float)
  |> decode.field("COUNT", decode.int)
  |> decode.field("IS_ON", decode.bool)

let assert Ok(env) = glenv.load(decoder, definitions)

env.hello // "world"
env.foo // 1.0
env.count // 1
env.is_on // True
Search Document