Skip to main content

Mutation

To modify data in GraphQL you use mutations.

Mutation

A mutation is a write operation and has the following syntax:mutation [name] [variables] [directives] selection. Note: [] means optional. A very simple mutation which takes a single string argument might look like this:

mutation {
createUser(name: "Anton") {
id
name
}
}

and might return a JSON object like this:

{
"createUser": {
"id": "1",
"name": "Anton"
}
}

But what if the createUser method needs not 1 but 8 parameters? Extending the argument list is possible, but seems not to be the best option. Luckily we can pass an object as argument. For this to work, the schema needs to have the proper input type defined.

Input Type

It is best practise to only have one argument when using mutations. So whenever we would need 2 arguments, we should create an input-type like below:

input CreateUserInput {
name: String!
age: Int!
height: Float!
}

type Mutation {
createUser(input: CreateUserInput!): User!
}

Important: A mutation cannot reference a custom type, e.g. User, in the argument list. It must be an input-type. The reason is that input-types can only consist of scalar values! So whenever we need to work with a nested object as argument, we need to define the proper input-type for each non-scalar value (object). Note: For an update operation we would define the dedicated input-type UpdateUserInput and not reuse CreateUserInput.

So our mutation would look like:

mutation {
createUser(input: { name: "Anton", age: 42, height: 1.75 }) {
id
name
}
}

In the resolver we would then access the input object as follows:

const resolver = {
Mutation: {
createUser(parent, { input }) { // because the name of the argument is input -> createUser(input: CreateUserInput!)
const { name, age, height } = input;
...
}
}
}