HomeBack-End & DatabaseGraphQL Mutations

GraphQL Mutations

Till now we have only seen how to fetch data and gone quite deep into it.

Now let’s see the how we can update data i.e POST, PUT, DELETE requests

We need to use mutations for it.

Mutation also follow exact similar pattern as Query. Let’s define a mutation to add a new profile data

//mutations/profile.js

export default `
extend type Mutation {
    addProfile(name: String) : Profile
}
`

//resolvers/profile.js
import data from "../data"

export default {
    Mutation: {
        addProfile : async (_, {name }) => {
            return await data.addProfile(name)
        }
    }
}

//data/index.js

addProfile: async (name) => {
        let id = Math.round(Math.random(0, 100) * 100, 0)
        users.push({
            id,
            name
        })
        return { id, name }
    }

and this how the mutations looks like

https://github.com/nodeexcel/gql_tutorial/commit/1f4ebfa9093f97632eb822282e11f8a50fa2aa33

It’s as simple as that.

We can also have a much more defined mutation e.g let’s add to mutation to add a Todo using “InputType”

export default `
input TodoInput {
    task: String,
    isComplete: Boolean
}
extend type Mutation {
    addTodo(input: TodoInput): Todo
}

`

This is how the code looks now

https://github.com/nodeexcel/gql_tutorial/commit/b5269c69a626834c844d73f387e2ba9dfd326463

It’s very simple once you understand queries

Go through the official guide to understand this is more details

https://graphql.org/graphql-js/mutations-and-input-types/

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: