fun parseKeyDirectiveValue()

in graphql-dgs-codegen-core/src/main/kotlin/com/netflix/graphql/dgs/codegen/generators/EntitiesRepresentationTypeGeneratorUtils.kt [84:129]


    fun parseKeyDirectiveValue(keyDirective: List<String>): Map<String, Any> {
        data class Node(
            val key: String,
            val map: MutableMap<String, Any>,
            val parent: Node?,
        )

        val keys =
            keyDirective
                .map { ds ->
                    ds
                        .map { if (it == '{' || it == '}') " $it " else "$it" }
                        .joinToString("", "", "")
                        .split(" ")
                }.flatten()

        // handle simple keys and nested keys by constructing the path to each  key
        // e.g. type Movie @key(fields: "movieId") or type MovieCast @key(fields: movie { movieId } actors { name } }
        val mappedKeyTypes = mutableMapOf<String, Any>()
        var parent = Node("", mappedKeyTypes, null)
        var current = Node("", mappedKeyTypes, null)
        keys
            .filter { it != " " && it != "" }
            .forEach {
                when (it) {
                    "{" -> {
                        // push a new map for the next level
                        val previous = parent
                        parent = current
                        @Suppress("UNCHECKED_CAST")
                        current = Node("", current.map[current.key] as MutableMap<String, Any>, previous)
                    }
                    "}" -> {
                        // pop back to parent level
                        current = parent
                        parent = parent.parent!!
                    }
                    else -> {
                        // make an entry at the current level
                        current.map.putIfAbsent(it, mutableMapOf<String, Any>())
                        current = Node(it, current.map, parent)
                    }
                }
            }
        return mappedKeyTypes
    }