fireproofsocks/dotenvy

Feature: Add support for some Validation checks

fireproofsocks opened this issue · 3 comments

It may not be enough to cast the incoming ENV value to an Elixir data type using Dotenvy.Transformer.to!/2: sometimes the app will break if the value is wrong. For example: a negative number used for a database port or a random quote from Shakespeare when a subdomain was expected. In both cases, the basic Elixir data type was correct (an integer and a string, respectively), but the app would still break because the values are unusable. Adding validation checks would help strengthen the contract between the app and its environment.

Basic validations:

  • number ranges (e.g. gt (i.e. >), gte, between, etc.)
  • enum or in (only one of set of possible values is allowed)
  • regex: the (string) value must match the given regular expression
  • URL: the (string) value must be a valid URL (ugh... don't try a regex for this)

Rather than trying to fit this into the Dotenvy.env!/2 or Dotenvy.env!/3 functions, it might be clearer to pipe output, e.g.

import Dotenvy

config_value: env!("SOME_ENV", :string) |> match!(~r/^a-z{2, 10}$/),
x: env!("X", :string) |> in!(["a", "b", "c"]),
y: env!("SOME_ENV", :string) |> matches!(~r/^a-z{2, 10}$/),

that way it would be possible to chain together multiple rules if complex criteria exist.

If this does belong as an input to env!/2 or env!/3, that messes with the simplicity of the functions because there's no room for options when arity 3 is already taken.

lud commented

I would like to be able to pass a function as the type.

Basically: def to!(str, fun) when is_function(fun, 1), do: fun.(str)

I like that idea!

Resolved #6