Skip to content

Instantly share code, notes, and snippets.

@afsalthaj
Last active December 6, 2020 01:13
Show Gist options
  • Save afsalthaj/6603581e017c2c122c703946c6364493 to your computer and use it in GitHub Desktop.
Save afsalthaj/6603581e017c2c122c703946c6364493 to your computer and use it in GitHub Desktop.
// MANAGING/COMBINING MULTIPLE SOURCES, DIFFERENT KEYS IN EACH SOURCES etc IN ZIO-CONFIG
// .. A follow up on the questions during FS2020
final case class Config(username: String, age: Int)
// Same as val configSpec = magnolia.descriptor[Config]
val configSpec: ConfigDescriptor[Config] =
(string("username") |@| int("age"))(Config.apply, Config.unapply)
val configPgm1: ConfigDescriptor[Config] =
configSpec.mapKey(_.toUpperCase) // implies the following:
// It require all the keys to be upperCase,
// It is globally changing your config spec across all the sources.
// We might end up doing something like this with mapKey when dealing multiple sources.
// orElse here is at descriptor level
// However that may not be always what we looking for
val configPgm2: ConfigDescriptor[Config] =
configSpec.mapKey(_.toUpperCase).from(sysEnv) orElse
configSpec.mapKey(_.toLowerCase).from(cmdLine)
// The above logic implies all keys should be available in a source.
// Ex: It doest pick username from source1 and password from next source.
// On the other hand, configSource.convertKeys is much more flexible
// The following code implies, my source is a combination of multiple sources and each one has its own key strategies
// sysEnv is `ConfigSource` and `cmdLine` is `ConfigSource`
// orElse is at source level
val mergedSources: ConfigSource =
sysEnv.convertKeys(_.toUpperCase) orElse cmdLine.convertKeys(_.toLowerCase)
// Given this source to configSpec, each key will try from various sources with different rules for keys.
val configPgm3 = configSpec from mergedSource
// Obviously, then you pass this config to `read` action to read the config
```scala
read(configPgm3)
// yielding Righ(Config(user, 20))for example
```
// Another question during FS2020 was how do we combine multiple sources coz they give different types in return (Either, ZIO etc)
// For now, this example can be really useful for all the users having this doubt.
https://github.com/zio/zio-config/blob/add_example/examples/src/main/scala/zio/config/examples/MultipleSourcesComplexExample.scala
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment