In this section, we continue the GraphQL example by explaining how to set our GraphQL mutations to be transactional. That means, to automatically wrap our GraphQL mutations with a database transaction and either commit at the end, or rollback the transaction in case of a GraphQL error.
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 checkout
v0.1.0 as follows:
The GraphQL extensions provides a handler named
entgql.Transactioner that executes each GraphQL mutation in a
transaction. The injected client for the resolver is a transactional
Hence, GraphQL resolvers that uses
ent.Client won't need to be changed. In order to add it to our todo list application
we follow these steps:
1. Edit the
cmd/todo/main.go and add to the GraphQL server initialization the
entgql.Transactioner handler as
2. Then, in the GraphQL mutations, use the client from context as follows:
Great! With a few lines of code, our application now supports automatic transactional mutations. Please continue to the next section where we explain how to extend the Ent code generator and generate GraphQL input types for our GraphQL mutations.