Packages

A library for declaratively reading, validating, and casting environment variables into their proper Elixir types in runtime.exs.

Current section

Files

Jump to
env_guard lib env_guard.ex
Raw

lib/env_guard.ex

defmodule EnvGuard do
@external_resource "README.md"
@moduledoc "README.md"
|> File.read!()
|> String.split("<!-- MDOC -->")
|> Enum.fetch!(1)
alias EnvGuard.Cast
alias EnvGuard.Constraints
alias EnvGuard.Env
@type constraint :: EnvGuard.Types.constraint()
@type type :: EnvGuard.Types.type()
@spec test_var(String.t(), type, [constraint]) ::
{:ok, any()} | {:error, atom()} | {:error, atom(), String.t()}
def test_var(name, type, constraints) do
with {:ok, value} <- Env.fetch(name),
{:ok, value} <- Cast.cast(value, type),
{:ok, value} <- Constraints.check_constraints(value, type, constraints) do
{:ok, value}
else
{:error, :constraint_violation, err} ->
{:error, :constraint_violation, err}
{:error, :cast_fail, err} ->
{:error, :invalid_type, err}
{:error, :env_var_not_set} ->
{:error, :env_var_not_set}
end
end
end