TExcelTAD
Home › GraphQL › Mutations

Mutations

Queries read data. To create, update or delete something you send a mutation. Technically any resolver could change data, but by convention (and for good reasons, explained below) all writes go through fields of the special Mutation root type.

Defining mutations

Mutation fields look like query fields with arguments. They usually return the changed object, so the client can select the fields it needs to refresh its UI in the same round trip:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(`
  type Todo { id: ID!, text: String!, done: Boolean! }

  type Query {
    todos: [Todo!]!
  }

  type Mutation {
    addTodo(text: String!): Todo!
    toggleTodo(id: ID!): Todo
  }
`);

const todos = [];
let nextId = 1;

const rootValue = {
  todos: () => todos,
  addTodo: ({ text }) => {
    const todo = { id: String(nextId++), text, done: false };
    todos.push(todo);
    return todo;
  },
  toggleTodo: ({ id }) => {
    const todo = todos.find((t) => t.id === id);
    if (todo) todo.done = !todo.done;
    return todo;
  },
};

const run = async (source, variableValues) => {
  const result = await graphql({ schema, source, rootValue, variableValues });
  console.log(JSON.stringify(result.data));
};

await run('mutation Add($text: String!) { addTodo(text: $text) { id text } }', { text: 'Buy milk' });
await run('mutation Add($text: String!) { addTodo(text: $text) { id } }', { text: 'Write report' });
await run('mutation { toggleTodo(id: "1") { id done } }');
await run('{ todos { id text done } }');
{"addTodo":{"id":"1","text":"Buy milk"}}
{"addTodo":{"id":"2"}}
{"toggleTodo":{"id":"1","done":true}}
{"todos":[{"id":"1","text":"Buy milk","done":true},{"id":"2","text":"Write report","done":false}]}

The mutation keyword is required: { addTodo(...) } would be read as a query, and Query has no addTodo field.

Several mutations run in order

Query fields may be resolved in parallel, because reading has no side effects. Mutation fields at the top level are executed one after another, in the order written. That makes this safe:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(`
  type Account { owner: String!, balance: Int! }
  type Query { account: Account }
  type Mutation {
    deposit(amount: Int!): Account
    withdraw(amount: Int!): Account
  }
`);

const account = { owner: 'Grace', balance: 100 };
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const rootValue = {
  account: () => account,
  deposit: async ({ amount }) => {
    await wait(30);                 // slow "database"
    account.balance += amount;
    console.log(`deposit ${amount} -> ${account.balance}`);
    return { ...account };
  },
  withdraw: async ({ amount }) => {
    await wait(5);                  // faster, but still waits its turn
    account.balance -= amount;
    console.log(`withdraw ${amount} -> ${account.balance}`);
    return { ...account };
  },
};

const result = await graphql({
  schema,
  rootValue,
  source: `mutation {
    first: deposit(amount: 50) { balance }
    second: withdraw(amount: 120) { balance }
  }`,
});
console.log(JSON.stringify(result.data));
deposit 50 -> 150
withdraw 120 -> 30
{"first":{"balance":150},"second":{"balance":30}}

Even though withdraw is faster, it starts only after deposit finished. Aliases (first, second) let you call mutation fields more than once in one request.

Input objects for many arguments

When a mutation needs many values, group them in an input type (covered in detail in its own lesson). Clients then send one variable:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(`
  input NewEventInput {
    title: String!
    city: String!
    seats: Int = 50
  }
  type Event { id: ID!, title: String!, city: String!, seats: Int! }
  type Query { events: [Event!]! }
  type Mutation { createEvent(input: NewEventInput!): Event! }
`);

const events = [];

const rootValue = {
  events: () => events,
  createEvent: ({ input }) => {
    const event = { id: `evt-${events.length + 1}`, ...input };
    events.push(event);
    return event;
  },
};

const result = await graphql({
  schema,
  rootValue,
  source: `mutation Create($input: NewEventInput!) {
    createEvent(input: $input) { id title city seats }
  }`,
  variableValues: { input: { title: 'GraphQL Meetup', city: 'Utrecht' } },
});
console.log(JSON.stringify(result.data, null, 2));
{
  "createEvent": {
    "id": "evt-1",
    "title": "GraphQL Meetup",
    "city": "Utrecht",
    "seats": 50
  }
}

seats took its default value of 50 from the input type.

Naming conventions

Style Example
verb + noun, camelCase createEvent, updateUser, deleteComment
one input argument createEvent(input: CreateEventInput!)
return the affected object (or a payload type) Event! or CreateEventPayload!

Note: A Query resolver can technically modify data, and nothing in graphql-js stops it. Don't do it: clients, caches and tools assume queries are safe to repeat, retry and run in parallel.

Test yourself

How are top-level mutation fields executed?

  1. In parallel
  2. In random order
  3. Serially, in the order written
  4. Alphabetically

Why do mutations usually return the changed object?

  1. It is required by the spec
  2. So the client can fetch updated fields in the same request
  3. To make them faster
  4. Because mutations can't have arguments

What happens if you send { addTodo(text: "x") { id } } without the mutation keyword?

  1. It runs as a mutation anyway
  2. It is treated as a query and fails validation
  3. It is ignored
  4. It runs twice