Understanding the GraphQL AST.

So what is an Abstract Syntax Tree?

As Stephen Schneider puts in ‘The GraphQL AST— Dawn of a schema’, an AST is just a ‘fancy way of saying heavily nested objects’. It is a structure that is commonly used in compilers to parse the code we write, converting it into a tree structure that we can traverse programmatically.

  • parent — Otherwise known as the root — since resolvers can delegate to other resolvers this argument contains the result of the previous call
  • args — parameters requested by the user for the query
  • context — ‘global’ variable passed through the resolver chain. Useful for communicating between different layers
  • info — This is our crown jewel. This is our AST
  • fieldName: the name of the current resolver
  • fieldNodes: an array of fields left in the current selectionSet (group of fields on current object we are traversing in the tree)
  • path: Keeps track of all the parent fields that led to the current branch
  • operation: The entire query info. (this is a global field that will be the same for any resolver. Other global fields include schema, fragments, rootValueand variableValues.

So why is all this important?

When I first starting implementing a GraphQL backend, my thoughts were not “I can’t wait until I can dive into that confusing GraphQL AST that I keep seeing scattered throughout my resolvers”.

  • Schema stitching
  • Custom directives
  • Enriched queries
  • Layered Abstraction
  • More backend magic!

Custom Directives

In a step to give more control to the front-end client, we often find it useful to implement a range of directives that can transform or filter out fields specified in the AST.

Caching

What nightmares are made of.

Conclusion

Understanding how the AST is structured and used within your resolvers allows you to gain a fine-grain control over the input and output of your GraphQL backend. It allows you to cache results, create custom directives, optimise queries & stitch together data from multiple resources.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adam Hannigan

Adam Hannigan

Creator of Sunflower Land. Come help us build the future of Web3 gaming! https://github.com/sunflower-land/sunflower-land