Scala environment config with typed validation
Scala
case class DbConfig(url: String, port: Int, poolSize: Int)
def loadDbConfig(env: String => Option[String] = sys.env.get): Either[List[String], DbConfig] =
def required(key: String): Either[List[String], String] =
env(key).filter(_.nonEmpty).toRight(s"$key is required").left.map(List(_))
def int(key: String, default: Int, valid: Int => Boolean): Either[List[String], Int] =
env(key).filter(_.nonEmpty) match
case None => Right(default)
case Some(raw) =>
raw.toIntOption.filter(valid).toRight(s"$key has an invalid integer value").left.map(List(_))
for
url <- required("DB_URL")
port <- int("DB_PORT", 5432, p => p > 0 && p < 65536)
pool <- int("DB_POOL_SIZE", 8, _ > 0)
yield DbConfig(url, port, pool)