Last active
January 17, 2023 10:50
-
-
Save pgollangi/fe4de4f192a8e993e1345b569891762b 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
""" | |
Python script that converts GraphQL query to dictionary using graphql-core python package | |
""" | |
from graphql import parse | |
from graphql.language import ast | |
def node_to_dict(node: ast.Node) -> dict: | |
""" | |
Convert GraphQL AST Node into dictionary | |
:param node: GraphQL AST Node | |
:return: result dictionary | |
""" | |
if node.kind == "document": | |
doc: ast.DocumentNode = node | |
defs = {} | |
for definition in doc.definitions: | |
defs = {**defs, **node_to_dict(definition)} | |
return defs | |
if node.kind == "operation_definition": | |
op: ast.OperationDefinitionNode = node | |
if op.operation == ast.OperationType.QUERY: | |
return {op.operation.value: node_to_dict(op.selection_set)} | |
elif node.kind == "selection_set": | |
ss: ast.SelectionSetNode = node | |
selections = ss.selections | |
sel_dict = {} | |
for selection in selections: | |
sel_dict = {**sel_dict, **node_to_dict(selection)} | |
return sel_dict | |
elif node.kind == "field": | |
field: ast.FieldNode = node | |
args = {} | |
for arg in field.arguments: | |
args = {**args, **node_to_dict(arg)} | |
value = {'__args': args} if len(args) else {} | |
if field.selection_set is not None: | |
value = {**value, **node_to_dict(field.selection_set)} | |
else: | |
value = True | |
return {field.name.value: value} | |
elif node.kind == "argument": | |
arg: ast.ArgumentNode = node | |
return {arg.name.value: arg.value.value} | |
root_node = parse(""" | |
query GetProjects { | |
projects (id: 50){ | |
edges { | |
node { | |
id | |
name | |
nameWithNamespace | |
fullPath | |
codeCoverageSummary { | |
averageCoverage | |
} | |
} | |
} | |
} | |
}""") | |
result = node_to_dict(root_node) | |
print(result) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment