Mutation Inputs

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.

Clone the code (optional)

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:

  1. git clone git@github.com:a8m/ent-graphql-example.git
  2. cd ent-graphql-example
  3. go run ./cmd/todo/

Mutation Types

Ent supports generating mutation types. A mutation type can be accepted as an input for GraphQL mutations, and it is handled and verified by Ent. Let’s tell Ent that our GraphQL Todo type supports create and update operations:

ent/schema/todo.go

  1. func (Todo) Annotations() []schema.Annotation {
  2. return []schema.Annotation{
  3. entgql.QueryField(),
  4. entgql.Mutations(entgql.MutationCreate(), entgql.MutationUpdate()),
  5. }
  6. }

Then, run code generation:

  1. go generate .

You’ll notice that Ent generated for you 2 types: ent.CreateTodoInput and ent.UpdateTodoInput.

Mutations

After generating our mutation inputs, we can connect them to the GraphQL mutations:

todo.graphql

  1. type Mutation {
  2. createTodo(input: CreateTodoInput!): Todo!
  3. updateTodo(id: ID!, input: UpdateTodoInput!): Todo!
  4. }

Running code generation we’ll generate the actual mutations and the only thing left after that is to bind the resolvers to Ent.

  1. go generate .

todo.resolvers.go

  1. // CreateTodo is the resolver for the createTodo field.
  2. func (r *mutationResolver) CreateTodo(ctx context.Context, input ent.CreateTodoInput) (*ent.Todo, error) {
  3. return r.client.Todo.Create().SetInput(input).Save(ctx)
  4. }
  5. // UpdateTodo is the resolver for the updateTodo field.
  6. func (r *mutationResolver) UpdateTodo(ctx context.Context, id int, input ent.UpdateTodoInput) (*ent.Todo, error) {
  7. return r.client.Todo.UpdateOneID(id).SetInput(input).Save(ctx)
  8. }

Test the CreateTodo Resolver

Let’s start with creating 2 todo items by executing the createTodo mutations twice.

Mutation

  1. mutation CreateTodo {
  2. createTodo(input: {text: "Create GraphQL Example", status: IN_PROGRESS, priority: 2}) {
  3. id
  4. text
  5. createdAt
  6. priority
  7. parent {
  8. id
  9. }
  10. }
  11. }

Output

  1. {
  2. "data": {
  3. "createTodo": {
  4. "id": "1",
  5. "text": "Create GraphQL Example",
  6. "createdAt": "2021-04-19T10:49:52+03:00",
  7. "priority": 2,
  8. "parent": null
  9. }
  10. }
  11. }

Mutation

  1. mutation CreateTodo {
  2. createTodo(input: {text: "Create Tracing Example", status: IN_PROGRESS, priority: 2}) {
  3. id
  4. text
  5. createdAt
  6. priority
  7. parent {
  8. id
  9. }
  10. }
  11. }

Output

  1. {
  2. "data": {
  3. "createTodo": {
  4. "id": "2",
  5. "text": "Create Tracing Example",
  6. "createdAt": "2021-04-19T10:50:01+03:00",
  7. "priority": 2,
  8. "parent": null
  9. }
  10. }
  11. }

Test the UpdateTodo Resolver

The only thing left is to test the UpdateTodo resolver. Let’s use it to update the parent of the 2nd todo item to 1.

  1. mutation UpdateTodo {
  2. updateTodo(id: 2, input: {parentID: 1}) {
  3. id
  4. text
  5. createdAt
  6. priority
  7. parent {
  8. id
  9. text
  10. }
  11. }
  12. }

Output

  1. {
  2. "data": {
  3. "updateTodo": {
  4. "id": "2",
  5. "text": "Create Tracing Example",
  6. "createdAt": "2021-04-19T10:50:01+03:00",
  7. "priority": 1,
  8. "parent": {
  9. "id": "1",
  10. "text": "Create GraphQL Example"
  11. }
  12. }
  13. }
  14. }

Create edges with mutations

To create the edges of a node in the same mutation, you can extend the GQL mutation input with the edge fields:

extended.graphql

  1. extend input CreateTodoInput {
  2. createChildren: [CreateTodoInput!]
  3. }

Next, run code generation again:

  1. go generate .

GQLGen will generate the resolver for the createChildren field, allowing you to use it in your resolver:

extended.resolvers.go

  1. // CreateChildren is the resolver for the createChildren field.
  2. func (r *createTodoInputResolver) CreateChildren(ctx context.Context, obj *ent.CreateTodoInput, data []*ent.CreateTodoInput) error {
  3. panic(fmt.Errorf("not implemented: CreateChildren - createChildren"))
  4. }

Now, we need to implement the logic to create the children:

extended.resolvers.go

  1. // CreateChildren is the resolver for the createChildren field.
  2. func (r *createTodoInputResolver) CreateChildren(ctx context.Context, obj *ent.CreateTodoInput, data []*ent.CreateTodoInput) error {
  3. // NOTE: We need to use the Ent client from the context.
  4. // To ensure we create all of the children in the same transaction.
  5. // See: Transactional Mutations for more information.
  6. c := ent.FromContext(ctx)
  7. builders := make([]*ent.TodoCreate, len(data))
  8. for i := range data {
  9. builders[i] = c.Todo.Create().SetInput(*data[i])
  10. }
  11. todos, err := c.Todo.CreateBulk(builders...).Save(ctx)
  12. if err != nil {
  13. return err
  14. }
  15. ids := make([]int, len(todos))
  16. for i := range todos {
  17. ids[i] = todos[i].ID
  18. }
  19. obj.ChildIDs = append(obj.ChildIDs, ids...)
  20. return nil
  21. }

Change the following lines to use the transactional client:

todo.resolvers.go

  1. // CreateTodo is the resolver for the createTodo field.
  2. func (r *mutationResolver) CreateTodo(ctx context.Context, input ent.CreateTodoInput) (*ent.Todo, error) {
  3. return ent.FromContext(ctx).Todo.Create().SetInput(input).Save(ctx)
  4. }
  5. // UpdateTodo is the resolver for the updateTodo field.
  6. func (r *mutationResolver) UpdateTodo(ctx context.Context, id int, input ent.UpdateTodoInput) (*ent.Todo, error) {
  7. return ent.FromContext(ctx).Todo.UpdateOneID(id).SetInput(input).Save(ctx)
  8. }

Test the mutation with the children:

Mutation

  1. mutation {
  2. createTodo(input: {
  3. text: "parent", status:IN_PROGRESS,
  4. createChildren: [
  5. { text: "children1", status: IN_PROGRESS },
  6. { text: "children2", status: COMPLETED }
  7. ]
  8. }) {
  9. id
  10. text
  11. children {
  12. id
  13. text
  14. status
  15. }
  16. }
  17. }

Output

  1. {
  2. "data": {
  3. "createTodo": {
  4. "id": "3",
  5. "text": "parent",
  6. "children": [
  7. {
  8. "id": "1",
  9. "text": "children1",
  10. "status": "IN_PROGRESS"
  11. },
  12. {
  13. "id": "2",
  14. "text": "children2",
  15. "status": "COMPLETED"
  16. }
  17. ]
  18. }
  19. }
  20. }

If you enable the debug Client, you’ll see that the children are created in the same transaction:

  1. 2022/12/14 00:27:41 driver.Tx(7e04b00b-7941-41c5-9aee-41c8c2d85312): started
  2. 2022/12/14 00:27:41 Tx(7e04b00b-7941-41c5-9aee-41c8c2d85312).Query: query=INSERT INTO `todos` (`created_at`, `priority`, `status`, `text`) VALUES (?, ?, ?, ?), (?, ?, ?, ?) RETURNING `id` args=[2022-12-14 00:27:41.046344 +0700 +07 m=+5.283557793 0 IN_PROGRESS children1 2022-12-14 00:27:41.046345 +0700 +07 m=+5.283558626 0 COMPLETED children2]
  3. 2022/12/14 00:27:41 Tx(7e04b00b-7941-41c5-9aee-41c8c2d85312).Query: query=INSERT INTO `todos` (`text`, `created_at`, `status`, `priority`) VALUES (?, ?, ?, ?) RETURNING `id` args=[parent 2022-12-14 00:27:41.047455 +0700 +07 m=+5.284669251 IN_PROGRESS 0]
  4. 2022/12/14 00:27:41 Tx(7e04b00b-7941-41c5-9aee-41c8c2d85312).Exec: query=UPDATE `todos` SET `todo_parent` = ? WHERE `id` IN (?, ?) AND `todo_parent` IS NULL args=[3 1 2]
  5. 2022/12/14 00:27:41 Tx(7e04b00b-7941-41c5-9aee-41c8c2d85312).Query: query=SELECT DISTINCT `todos`.`id`, `todos`.`text`, `todos`.`created_at`, `todos`.`status`, `todos`.`priority` FROM `todos` WHERE `todo_parent` = ? args=[3]
  6. 2022/12/14 00:27:41 Tx(7e04b00b-7941-41c5-9aee-41c8c2d85312): committed