Skip to content

Instantly share code, notes, and snippets.

@martinbonnin
Created May 23, 2022 10:55
Show Gist options
  • Save martinbonnin/11a008751cf32da9181c95cf6493fbe4 to your computer and use it in GitHub Desktop.
Save martinbonnin/11a008751cf32da9181c95cf6493fbe4 to your computer and use it in GitHub Desktop.
@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
email
}
}
""".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