uk.co.unclealex.diagnostics.ConfigurationExtensions.scala Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of play-diagnostics_2.13 Show documentation
Show all versions of play-diagnostics_2.13 Show documentation
Diagnostics for Play applications
package uk.co.unclealex.diagnostics
import play.api.{ConfigLoader, Configuration}
import scala.util.Try
/**
* Get configuration options and fall back to environment variables if they are not found.
*/
object ConfigurationExtensions {
implicit class ConfigurationWithEnvironment(configuration: Configuration) {
def getOrEnvOptional[T](configurationPropertyName: String, jvmPropertyName: String)
(implicit configLoader: ConfigLoader[T], propertyConverter: PropertyConverter[T]): Option[T] = {
val nullSafeFactory: (String => String) => Option[T] = {
propertyReader => for {
propertyAsString <- Option(propertyReader(jvmPropertyName))
propertyAsType <- Try(propertyConverter(propertyAsString)).toOption
} yield {
propertyAsType
}
}
configuration.getOptional[T](configurationPropertyName).
orElse(nullSafeFactory(System.getProperty)).
orElse(nullSafeFactory(System.getenv))
}
def getOrEnv[T](description: String, configurationPropertyName: String, jvmPropertyName: String)
(implicit configLoader: ConfigLoader[T], propertyConverter: PropertyConverter[T]): T = {
getOrEnvOptional[T](configurationPropertyName, jvmPropertyName) match {
case Some(value) => value
case None => throw new IllegalStateException(
s"You must provide a $description either as a '$configurationPropertyName' configuration option or as a '$jvmPropertyName' environment variable ")
}
}
}
sealed trait PropertyConverter[T] {
def apply(value: String): T
}
implicit val stringPropertyConverter: PropertyConverter[String] = new PropertyConverter[String] {
override def apply(value: String): String = value
}
implicit val intPropertyConverter: PropertyConverter[Int] = new PropertyConverter[Int] {
override def apply(value: String): Int = Integer.parseInt(value)
}
}