iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📑

Introduction to GraphQL Mutations

に公開
2026/05/17

Introduction

In the previous article, I introduced the basic mechanisms of GraphQL and how to create an API using gqlgen.

In this article, we will implement adding, modifying, and deleting Todos using Mutations.
Normally, you would need to set up a database, but in GraphQL, you can verify the behavior by keeping data in memory.


What is a Mutation?

In GraphQL, while Query is used for fetching data, Mutation is used when adding, updating, or deleting data.

In this article, we will add processes to create, update, and delete Todos.


Mutation Implementation Steps

1. Add Mutation to the Schema

Modify the type Mutation block in graph/schema.graphqls as follows:

type Mutation {
  createTodo(input: NewTodo!): Todo!
  updateTodo(id: ID!, text: String, done: Boolean): Todo
  deleteTodo(id: ID!): Boolean!
}

2. Define the Model

In graph/model/models_gen.go, you need to add the NewTodo type to receive new Todos, but it should already have been added as of the previous article.

package model

type NewTodo struct {
  Text   string `json:"text"`
  UserID string `json:"userId"`
}

With this, we have defined the data structure for the text and userId received from the client.


3. Implement the Resolver

Next, implement the processes for createTodo, updateTodo, and deleteTodo in graph/schema.resolvers.go.

Since we have modified the schema, delete graph/schema.resolvers.go and regenerate the resolvers.

go run github.com/99designs/gqlgen generate

Replace the content of graph/schema.resolvers.go with the following source code.

package graph

// This file will be automatically regenerated based on the schema, any resolver implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.66

import (
	"context"
	"example/graph/model"
	"fmt"
)

// Sample users
var users = []*model.User{
	{ID: "1", Name: "Alice"},
	{ID: "2", Name: "Bob"},
}

// Sample Todos
var todos = []*model.Todo{
	{ID: "1", Text: "Alice Todo", Done: false, User: users[0]},
	{ID: "2", Text: "Bob Todo", Done: true, User: users[1]},
}

// Implement the `createTodo` resolver
func (r *mutationResolver) CreateTodo(ctx context.Context, input model.NewTodo) (*model.Todo, error) {
	newTodo := &model.Todo{
		ID:   fmt.Sprintf("%d", len(todos)+1),
		Text: input.Text,
		Done: false,
		User: &model.User{ID: input.UserID, Name: "Unknown"},
	}

	todos = append(todos, newTodo)
	return newTodo, nil
}

// Implement the `updateTodo` resolver
func (r *mutationResolver) UpdateTodo(ctx context.Context, id string, text *string, done *bool) (*model.Todo, error) {
	for _, todo := range todos {
		if todo.ID == id {
			if text != nil {
				todo.Text = *text
			}
			if done != nil {
				todo.Done = *done
			}
			return todo, nil
		}
	}
	return nil, fmt.Errorf("todo not found")
}

// Implement the `deleteTodo` resolver
func (r *mutationResolver) DeleteTodo(ctx context.Context, id string) (bool, error) {
	for i, todo := range todos {
		if todo.ID == id {
			todos = append(todos[:i], todos[i+1:]...)
			return true, nil
		}
	}
	return false, fmt.Errorf("todo not found")
}

// `todos` resolver (fetches all Todos)
func (r *queryResolver) Todos(ctx context.Context) ([]*model.Todo, error) {
	return todos, nil
}

// Mutation returns MutationResolver implementation.
func (r *Resolver) Mutation() MutationResolver { return &mutationResolver{r} }

// Query returns QueryResolver implementation.
func (r *Resolver) Query() QueryResolver { return &queryResolver{r} }

type mutationResolver struct{ *Resolver }
type queryResolver struct{ *Resolver }



4. Start the Server and Execute Mutations

go run server.go

In the GraphQL Playground, execute the following Mutations to verify if the data is modified.

Create Todo

mutation {
  createTodo(input: { text: "Added Alice's Todo", userId: "1" }) {
    id
    text
    done
    user {
      id
      name
    }
  }
}

Update Todo

mutation {
  updateTodo(id: "1", text: "Updated Alice's Todo", done: true) {
    id
    text
    done
  }
}

Delete Todo

mutation {
  deleteTodo(id: "2")
}

Verify Results

Execute the following to verify the addition, update, and deletion:

query {
  todos {
    id
    text
    done
    user {
      id
      name
    }
  }
}

Discussion