Configuration with PureConfig

We're already familiar with the Typesafe Config library, which we actively used in our bakery examples. It is a very useful and flexible library. Unfortunately, because of this flexibility, it has one shortcoming: each configuration bit needs to be read and converted to the appropriate type individually. Ideally, we'd like our configuration to be represented as case classes and rely on naming conventions to map the structure of the configuration file to the structure of the (typed) configuration we have in the application. Ideally, we'd like to fail fast at startup time if the configuration file can't be mapped to the case classes that describe the configuration at the code level. 

The pureconfig library makes this possible. This library can be found at https://github.com/pureconfig/pureconfig.

Using it, we can define the configuration structure in Scala like the following:

case class ServerConfig(host: String, port: Int)
case class DBConfig(driver: String, url: String, user: String, password: String)
case class Config(server: ServerConfig, database: DBConfig)

This definition reflects the structure of the configuration in HOCON format:

server {
host = "0.0.0.0"
port = 8080
}
database {
driver = "org.h2.Driver"
url = "jdbc:h2:mem:ch14;DB_CLOSE_DELAY=-1"
user = "sa"
password = ""
}

Now we can load and map it to the case classes directly using pureconfig:

object Config {
def load(fileName: String): IO[Config] = {
IO {
val config = ConfigFactory.load(fileName)
pureconfig.loadConfig[Config](config)
}.flatMap {
case Left(e) =>
IO.raiseError[Config](new ConfigReaderException[Config](e))
case Right(config) =>
IO.pure(config)
}
}
}

Again, wrapped in IO and thus delayed, we're trying to load and map the configuration and raise an appropriate error in the context of an IO in the case this attempt has failed.

The configuration bit concludes the infrastructural part of the example and we can finally turn to the coreā€”the database repository.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.36.146