Go GraphQL: Implementing the GraphQL Mutations in Golang #4

In this post, we will learn how to write GraphQL mutations to manipulate the data at server



In this section, you’ll learn how to add a mutation to the GraphQL API. This mutation will allow you to post new Human character to the server.

Lets get started!!
. . .

Extending the schema definition

In general, when adding a new feature to the API, the process will look pretty similar every time:
  1. Extend the GraphQL schema definition with a new root field ( in our case it will be mutation)
  2. Implement corresponding resolver functions for the added fields ( mutation )
This process is also referred to as schema-driven or schema-first development. So, let’s go ahead and tackle the first step, extending the GraphQL schema definition.
. . .

Adding createHuman Mutation

Let’s start by implementing a createHuman mutation that allows you to post a new Human character to the server, first, we will be adding proper fields to accept the mutation, then we will add the resolver function to resolve the mutation
1. Define Schema
So, let’s go ahead and tackle the first step, extending the GraphQL schema definition by adding the createHuman mutation.

Mutation := graphql.NewObject(graphql.ObjectConfig{
Name: "Mutation",
Fields: graphql.Fields{
#1
"createHuman": &graphql.Field{
Type: types.HumanType,
Description: "create human character",
#2
Args: graphql.FieldConfigArgument{
"id": &graphql.ArgumentConfig{
Description: "id of the human",
Type: graphql.NewNonNull(graphql.Int),
},
"name": &graphql.ArgumentConfig{
Description: "new name of the human",
Type: graphql.NewNonNull(graphql.String),
},
"homePlanet": &graphql.ArgumentConfig{
Description: "new home planet of the human",
Type: graphql.NewNonNull(graphql.String),
},
"appearsIn": &graphql.ArgumentConfig{
Description: "new episodes of the human",
Type: graphql.NewList(graphql.Int),
},
},
#3
Resolve: func(params graphql.ResolveParams) (interface{}, error) {
... resolver code
},
},
},
})

Let’s walk through the numbered comments again:
  1. first, we have added to createHuman mutation to the schema, which creates a new human character and returns the same
  2. createHuman mutation accepts the four filed arguments which we have defined into the field args, it accepts the Id, name, homePlanet, appearsIn as its arguments
  3. Next, we have added the resolver function to resolve the mutation

2. Implement resolver functions
The next step is to implement the resolver function for the createHuman mutation. In fact, one thing we haven’t mentioned yet is that not only root fields, but virtually all fields on the types in a GraphQL schema have resolver functions.

#1
Resolve: func(params graphql.ResolveParams) (interface{}, error) {
#2
// marshall and cast the argument value
id, _ := params.Args["id"].(int)
name, _ := params.Args["name"].(string)
homePlanet, _ := params.Args["homePlanet"].(string)
appearsIn, _ := params.Args["appearsIn"].([]interface{})

// type assertion to convert []interface to []int
appearsin := make([]int, len(appearsIn))
for i := range appearsin {
appearsin[i] = appearsIn[i].(int)
}
#3
return resolvers.CreatePerson(id, name, appearsin, homePlanet), nil
}

Let’s walk through the numbered comments again:
  1. We have added the resolver function to resolve the mutation
  2. Inside the resolver function, we have access to all the fields that we have defined in the arguments while adding mutation in our schema
  3. We are calling the resolver function which will add a new Human character to the server and will return the same

Go ahead and test the implementation by restarting the server (first use CTRL+C to stop the server if it is still running, then execute go run main.go again) and navigate to http://localhost:8080in your browser.

If you expand the documentation of the Playground, you’ll notice that another mutation called createHuman is now available:

Now its time to test our mutation to see it in action!
. . .

Testing the mutation

Go ahead and restart your server so you can test the new API operations. Here is a sample mutation you can send through the Playground:
mutation {
createHuman (
id: 1005,
name: "Luke Skywalker -II"
appearsIn: [3,6]
homePlanet: "Alderaa"
) {
id
name
appearsIn
homePlanet
}
}

The server response will look as follows:
{
"data": {
"createHuman": {
"appearsIn": [
null,
"JEDI"
],
"homePlanet": "Alderaa",
"id": "1005",
"name": "Luke Skywalker -II"
}
}
}

To verify that your mutation worked, you can send the Humans query from before again - it now returns the additional Human that you created with the mutation:

However, once you kill and restart the server, you’ll notice that the previously added Humans are now gone and you need to add them again. This is because the links are only stored in-memory, in the links array.
. . .


Never miss a post from Gufran Mirza, when you sign up for Ednsquare.