Mutations in GraphQL

It’s time to describe how to write and query a simple mutation.

So far we have seen how you can prepare queries to read your data. Time to mutate some data.

The GraphQLSchema exposes 2 subtrees:

export var Schema = new GraphQLSchema({
  query: queryType,
  mutation: mutationType
});

The simplest mutation you can think of is a mutation with no arguments which would increment a counter right?

Here it is:

var count = 0;
let mutationType = new GraphQLObjectType({
  name: 'RootMutationType',
  fields: {
    updateCount: {
      type: GraphQLInt,
      description: 'Updates the count',
      resolve: function() {
        count += 1;
        return count;
      }
    }
  }
});

You can trigger this mutation using the mutation keyword:

mutation test {
  updateCount
}

and the result is :

{
  "data": {
    "updateCount": 48
  }
}

mutation vs query

Hum… it so appears that there is a shorthand form for queries.

For instance, both request are valid:

query myQuery {
  podcast(id: "1") {
    id
    title
  }
}

but, in the shorthand form, you can omit the query keyword:

{
  podcast(id: "1") {
    id
    title
  }
}

For a mutation operation, you have to to start with the mutation keyword:

mutation test {
  updateCount
}

Not a huge deal, but I still wasted 10 mn of my life figuring that out :grimacing: