Most of the codegen's plugins are written with a design-pattern called Visitor. GraphQL has an internal mechanism for "visiting" a GraphQLSchema and GraphQL operations, and you can use it to transform your GraphQL definitions into a custom output.
With visitor pattern you can call a custom function on each AST node, and transform it into something else.
You can use ASTExplorer and see how does GraphQL represents it's definitions in a JSON structure, and you can also use this to understand which function will be called each time.
In graphql.org you can find the exact API documentation we are going to use in this section.
In this example, we will transform a basic type definition into a list of types and fields:
To get started with a basic visitor, start by extracting the
astNode of your
Note: if you wish to have GraphQL directives when you print your schema, use
Then, create your initial visitor, in our case, we would like to transform a
ObjectTypeDefinition, so let's create an object with a stub definitions, an use
visit to run it:
Now, let's implement
This repository also contains a set of utils that might help you to write plugins faster using visitor pattern.
All those utils are part of
It includes set of Visitor classes that you can use and extend, to implement your plugin easily:
BaseVisitoris a class that contains a very basic implementation and utils for plugin configuration, and let you easily implement plugins that compatiable with
scalarsconfiguration. Here you can find an example for using it.
BaseDocumentsVisitoris class that contains implementation for transforming GraphQL operations (query/mutation/subscription/fragment) with a resursive handler for selection-sets. It's the base implementation for
ClientSideBaseVisitoris a class that contains implementation for creating client-side code for consuming GraphQL operations, it's in use by
You can use the above classes as base, and extend it as you wish, to create a custom plugin.