juanchito
juanchito

Reputation: 521

Play (Scala) Configuration Map Object

I would like to access the following configuration

customers {
  "cust1" {
    clientId: "id1"
    attrs {
      att1: "str1"
      att2: "str2"
      att3: "str3"
      att4: "str4"
    }
  }
  "cust2" {
    clientId: "id2"
    attrs: {
      att1: "faldfjalfj"
      att2: "reqwrewrqrq"
    }
  }
  "cust3" {
    clientId: "id3"
    attrs {
      att2: "xvcbzxbv"
    }
  }
}

as a Map[String, CustomerConfig] where CustomerConfig is

package models

import play.api.ConfigLoader
import com.typesafe.config.Config // I added this import in order to make the documentation snippet compile to the best of my knowledge.

case class CustomerConfig(clientId: String, attrs: Map[String, String])

object CustomerConfig {
  implicit val configLoader: ConfigLoader[CustomerConfig] = new ConfigLoader[CustomerConfig] {
  def load(rootConfig: Config, path: String): CustomerConfig = {
    val config = rootConfig.getConfig(path)
    CustomerConfig(
      clientId = config.getString("clientId"),
      attrs = config.get[Map[String, String]]("attrs").map { case (attr, attrVal) =>
        (attr, attrVal)
      })
    }
  }
}

For reference, this is how I am currently attempting to reference it:

  val resellerEnvMap = conf.get[Map[String, CustomerConfig]]("customers").map {
    case (customer, customerConfig) =>
      customer -> customerConfig.attrs.map {
        case (attr, attrVal) =>
          attr -> new Obj(attrVal, customerConfig.clientId)
      }
  }

based on custom config loader documentation.

The problem is that config.get[A] does not exist (neither does config.getMap[K, V]) per the what I believe to be the API docs. I would like a way to populate that map from the configuration file. My end goal is to populate anything in the functional vicinity of Map[String, Map[String, (String, String)]] where the first String is the customer name, the 2nd is attribute name, the 3rd is the attribute value, and lastly, the 4th is the client ID.

Upvotes: 1

Views: 2511

Answers (1)

Jamie
Jamie

Reputation: 6114

Play 2.6 uses com.typesafe:config 1.3.2 while the link you posted seems to be from version 2? Here's one way to do it:

object CustomerConfig {
  implicit val configLoader: ConfigLoader[CustomerConfig] = new ConfigLoader[CustomerConfig] {
    def load(rootConfig: Config, path: String): CustomerConfig = {
      val config = rootConfig.getConfig(path)
      import scala.collection.JavaConverters._

      val attrConfig = config.getConfig("attrs")
      CustomerConfig(
        clientId = config.getString("clientId"),
        attrs = attrConfig.entrySet().asScala.map { entry =>
          (entry.getKey, attrConfig.getString(entry.getKey))
        }.toMap
      )
    }
  }
}

Upvotes: 5

Related Questions