In this section, we continue the GraphQL example by explaining how to extend the Ent code generator using Go templates and generate input type objects for our GraphQL mutations that can be applied directly on Ent mutations.
The code for this tutorial is available under github.com/a8m/ent-graphql-example, and tagged (using Git) in each step. If you want to skip the basic setup and start with the initial version of the GraphQL server, you can clone the repository and run the program as follows:
The Ent framework accepts external templates that can extend or override the default generated functionality of its
code generator. In the template below, we generate 2 input types (
UpdateTodoInput) for the
GraphQL mutations, and add additional methods on the different builders to accept these objects as an input type.
The full version of this template exists in the github.com/a8m/ent-graphql-example/ent/template.
Now, we tell the Ent code generator to execute this template by passing it as an argument in the
After adding the template file to the
ent/template/ directory and changing the
entc.go configuration, we're ready
to execute the code generation as follows:
You may have noticed that Ent generated a new file
ent/mutation_input.go with the following content:
The new generated Go types are the GraphQL mutation types. Let's define them manually in the GraphQL schema and
will map them automatically.
We're ready now to run the
gqlgen code generator and generate resolvers for the new mutations.
The result is as follows:
Apply Input Types on
Set<F> calls in the
CreateTodo resolver are replaced with one call named
The rest of the resolvers (
UpdateTodos) will be implemented as follows:
Hurray! We're now ready to test our GraphQL resolvers.
Let's start with creating 2 todo items by executing this query with the variables below:
We continue the example by updating the
priority of the 2 todo items to
The only thing left is to test the
UpdateTodo resolver. Let's use it to update the
parent of the 2nd todo item to