Advertisement
mitrakov

Scala Play: reading conf

Mar 5th, 2018
398
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.18 KB | None | 0 0
  1. // Let's read config with custom types (see basic example at https://pastebin.com/1hFjBN1A)
  2.  
  3. // TestController.scala
  4. import javax.inject.Inject
  5. import play.api.Configuration
  6. import play.api.mvc._
  7.  
  8. class TestController @Inject()(
  9.     cc: ControllerComponents,
  10.     appConf: Configuration
  11.   )extends AbstractController(cc) {
  12.  
  13.   val reportsName: Option[String] = appConf.get[Option[String]]("students.reports.name")
  14.   val lastException: Option[Exception] = appConf.get[Option[Exception]]("students.reports.exception")
  15.  
  16.   // add to routes file: GET    /testConfig    controllers.TestController.testConfig
  17.   def testConfig: Action[AnyContent] = Action(parse.json) {
  18.     Ok(s"Name: $reportsName; Last error: $lastException")
  19.   }
  20. }
  21.  
  22. // application conf:
  23. students.reports {
  24.   name = "qwerty"
  25.   exception = "Smth not found"
  26. }
  27.  
  28.         // Compile output:
  29.         // Error:(13, 72) could not find implicit value for parameter loader: play.api.ConfigLoader[Option[Exception]]
  30.         //  val lastException: Option[Exception] = appConf.get[Option[Exception]]("students.reports.exception")
  31.  
  32. // We must create custom loader for java.lang.Exception type.
  33. // Let's create a loader for a common case: for our case class
  34. import javax.inject.Inject
  35. import com.typesafe.config.Config
  36. import play.api.{ConfigLoader, Configuration}
  37. import play.api.mvc._
  38.  
  39. class TestController @Inject()(
  40.     cc: ControllerComponents,
  41.     appConf: Configuration
  42.   ) extends AbstractController(cc) {
  43.  
  44.   case class MyConfig(reportsName: String, lastException: Exception)
  45.  
  46.   implicit val cfgLoader = new ConfigLoader[MyConfig] {
  47.     override def load(config: Config, path: String): MyConfig = {
  48.       val conf = config.getConfig(path)
  49.       MyConfig(conf.getString("name"), new Exception(conf.getString("exception")))
  50.     }
  51.   }
  52.  
  53.   val myCfg: Option[MyConfig] = appConf.get[Option[MyConfig]]("students.reports")
  54.  
  55.   // add to routes file: GET    /testConfig    controllers.TestController.testConfig
  56.   def testConfig: Action[AnyContent] = Action(parse.json) {
  57.     Ok(s"Result: $myCfg")
  58.   }
  59. }
  60.  
  61. // Output:
  62. // http://localhost:9000/testConfig
  63. // Result: Some(MyConfig(qwerty,java.lang.Exception: Smth not found))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement