Reputation: 4175
I'm trying to use python to parse a graphql query, alter it, and turn it back into a string query that I can pass to the graphql server.
Specifically, I'm trying to ensure that a query will always have the pageInfo
paging information, so if I'm executing a query, I will always be able to automatically page through the results, even if a user might forget that stanza in their actual query.
It seems surprisingly difficult to parse a graphql query into something useful, and then be able to go from the parsed data representation back to the query string. Is there a library that google isn't able to turn up for me?
Thanks so much for any help!
Upvotes: 3
Views: 5105
Reputation: 219
I've just faced a similar problem. For future reference: the way you edit the AST is by creating a visitor class that will enter the tree and modify it to your liking. It's described in the documentation here. For example, in order to remove field named attributes
I used following code:
from graphql import parse, print_ast
from graphql.language.visitor import visit, Visitor, REMOVE, IDLE
class RemoveAttributesVisitor(Visitor):
def enter_field(self, node, key, parent, path, ancestors):
if node.name.value == "attributes":
return REMOVE
return IDLE
ast = parse(PRODUCT_QUERY)
new_ast = visit(ast, RemoveAttributesVisitor())
updated_query = print_ast(new_ast)
Upvotes: 1
Reputation: 84857
The core library includes a parse
function for parsing strings into AST and a print_ast
function for converting the AST back to a string.
Upvotes: 3