Hi, we're interested in loading an `Environment` f...
# http4k
c
Hi, we're interested in loading an
Environment
from a
.yaml
in the classpath, but I see there's only
Environment.fromYaml(file: File)
and classpath support can only be used for
.properties
files. Is there a way to do this that I might be missing?
d
It doesn’t exist so far, you could implement your own extension, like the one
Environment.fromYaml(file: File)
Copy code
//Completely untested:
fun Environment.Companion.fromYamlResource(resource: String): Environment {
    val map = Companion::class.java.getResourceAsStream("/${resource.removePrefix("/")}")
        ?.let { r -> JacksonYaml.asA<Map<String, Any>>(r.reader().use { it.readText() }) } 
        ?: throw FileNotFoundException(resource)

    fun Map<*, *>.flatten(): List<Pair<String, String>> {
        fun convert(key: Any?, value: Any?): List<Pair<String, String>> {
            val keyString = (key ?: "").toString()

            return when (value) {
                is List<*> -> listOf(keyString to value.flatMap { convert(null, it) }.joinToString(",") { it.second })
                is Map<*, *> -> value.flatten().map { "$keyString.${it.first}" to it.second }
                else -> listOf((keyString to (value ?: "").toString()))
            }
        }

        return entries.fold(listOf()) { acc, (key, value) -> acc + convert(key, value) }
    }

    return MapEnvironment.from(map.flatten().toMap().toProperties())
}
it’s not nice since it’s copied from several function within cloudnativ module - so it doesn’t qualifies a PR, maybe I’ll have some time later on
c
No worries, thanks!
d
Created a PR.
🙌 1