zio / zio-config

Easily use and document any config from anywhere in ZIO apps
https://zio.dev/zio-config
Apache License 2.0
231 stars 112 forks source link

Explain how to use this in a ZIO-Application #1411

Closed domdorn closed 4 months ago

domdorn commented 4 months ago

I'm having a hard time getting zio-config to run in my application... all the examples focus around mapping to custom data types, while I just want to use the ZIO.config(...) way to access a registered config..

Please see this simplified test to see what I want to achieve as a minimum.


import com.typesafe.config
import zio.Config
import zio.ConfigProvider
import zio.Scope
import zio.ZIO
import zio.config.typesafe.FromConfigSourceTypesafe
import zio.test.Spec
import zio.test.TestAspect
import zio.test.TestEnvironment
import zio.test.ZIOSpecDefault

object ConfigSpec extends ZIOSpecDefault {

  override def spec: Spec[TestEnvironment with Scope, Any] = suite("ConfigSpec")(
    test("test1") {
      for {
        _ <- zio.ZIO.unit
        value <- ZIO.config(Config.string("myService.group.variable"))
      } yield zio.test.assertTrue(value == "value")
    }
  ) @@ TestAspect.withConfigProvider({
    // expect here a externally provided typesafe config object
    val c: config.Config = com.typesafe.config.ConfigFactory.parseString(
      s"""
         |myService {
         |  group {
         |    variable = "value"
         |  }
         |
         |}
         |
         |""".stripMargin)
    println(c)
    val cp = ConfigProvider.fromTypesafeConfig(c, false)

    cp
  })
}

Thanks, Dominik

domdorn commented 4 months ago

nevermind.. got it working.. key was using the Nested class, like this:

userAgent <- ZLayer.fromZIO(ZIO.config(Config.Nested("akka", Config.Nested("http", Config.Nested("client", Config.string("user-agent-header"))))))

later I figured out, I can use it like this as well:

userAgent <- ZIO.config(Config.string("user-agent-header").nested("akka", "http", "client"))