Created
May 23, 2022 10:55
-
-
Save martinbonnin/11a008751cf32da9181c95cf6493fbe4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Test | |
fun validate() { | |
val schemaString = """ | |
type Query { | |
user: User! | |
} | |
type User { | |
firstName: String! | |
lastName: String! | |
email: String! | |
} | |
""".trimIndent() | |
val queryString = """ | |
query GetUser { | |
user { | |
firstName | |
lastName | |
} | |
} | |
""".trimIndent() | |
val schema = schemaString.buffer().toSchema() | |
val operation = queryString.buffer().parseAsGQLDocument().value?.definitions?.first() as? GQLOperationDefinition ?: error("no operation found") | |
validate(schema, operation.selectionSet, "Query", "data") | |
} | |
private fun validate(schema: Schema, selectionSet: GQLSelectionSet, parentType: String, path: String) { | |
val fieldNames: Set<String> = selectionSet.selections.filterIsInstance<GQLField>().map { it.name }.toSet() | |
if (fieldNames.contains("firstName") | |
&& fieldNames.contains("lastName") | |
&& fieldNames.contains("email") | |
&& parentType == "User" | |
) { | |
error("operation should use fragment ...userFragment instead of querying individual fields at: $path") | |
} | |
selectionSet.selections.forEach { | |
when (it) { | |
is GQLField -> { | |
if (it.selectionSet != null) { | |
val fieldDefinition = it.definitionFromScope(schema, parentType) ?: error("cannot find field definition for ${it.name} at $path") | |
validate(schema, it.selectionSet!!, fieldDefinition.type.leafType().name, "${path}.${it.responseName()}") | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment