Vapor validate Config Providers prior to loading

I want my app to search for configuration options at runtime with the following ascending precedence:

  • default config file “./config/config.toml”
  • system config file “/etc/my_app/config.toml”
  • env variables ["$MY_APP_CONFIG_KEY1", "$MY_APP_CONFIG_KEY2", ...]
  • user local config file “/home/$USER/.config/my_app/config.toml”

Based on the Precedence documentation in the Vapor docs:

Precedence
Vapor merges the configuration based on the order that the providers are specified.

providers = [
  %Dotenv{},
  %File{path: "$HOME/.vapor/config.json", bindings: []},
  %Env{bindings: []},
]

Env will have the highest precedence, followed by File, and finally Dotenv.

This seemed relatively straightforward, but the problem I have is that each provider specified must be valid. So if the user, for instance uses a TOML config but does not set the ENV variables specified in the bindings list the app will crash with a Vapor.LoadError. Would I need to validate the possible sources separately before adding them to the providers list that is passed to Vapor?

Haven’t worked with Vapor for like a year now so can’t exactly help you there but I’ve had a similar problem where I wanted to first check for an env var, then a local config file (in the current directory) and then a config file in $HOME. I just ended up writing my own small config provider that wrapped Vapor. Sadly I don’t have the code to share since that work was for a contract and not a personal project. But it was relatively easy to do.

Also, I might have stolen some code from the Rust config crate and translated it to Elixir in the process. :003:

1 Like