3. Adding a mutation to our schema2m

✍️ Updating our schema

To add a mutation, let's go to our schema in our server/src folder, in the schema.js file.

We'll start with the type keyword, then Mutation, followed by curly braces.

type Mutation {

We want to increment the number of views for a track, so we'll call this mutation incrementTrackViews. This mutation needs to know which track to update, so we'll open up parentheses, and inside, we add an argument called id. This argument's type is ID, and it's required, so we'll add an exclamation point (!) at the end.

incrementTrackViews(id: ID!)

We need a return type for this mutation. We could return a single Track because that's what this mutation updates, but as we saw in the previous lesson, there's a better approach.

Let's create a new type for our mutation response. Following convention, we'll combine the name of our mutation (IncrementTrackViews) with Response.

type IncrementTrackViewsResponse {

This type will have the three fields we mentioned earlier:

  • code (a non-nullable Int)
  • success (a non-nullable Boolean)
  • and message (a non-nullable String)

Finally, we'll add the objects that were modified. In our case, we only had one: track of type Track. Note that track can be null, because our mutation might fail.

Let's also add comments for each of these fields so that it makes our GraphQL API documentation more useful.

"Similar to HTTP status code, represents the status of the mutation"
code: Int!
"Indicates whether the mutation was successful"
success: Boolean!
"Human-readable message for the UI"
message: String!
"Newly updated track after a successful mutation"
track: Track
In the mutation response type (IncrementTrackViewsResponse), why is the modified object's return type nullable (track: Track)?

Lastly, we can set the return type of our mutation to this new IncrementTrackViewsResponse type, and make it non-nullable. Here's what the incrementTrackViews mutation should look like now:

type Mutation {
incrementTrackViews(id: ID!): IncrementTrackViewsResponse!
Code Challenge!

Add a mutation to this existing schema. The mutation should assign a spaceship to a specific mission. It should be called assignSpaceship. It takes in two required arguments: a spaceshipId of type ID!, and a missionId of type ID!. It should return a non-nullable type AssignSpaceshipResponse. This return type should return the three informational properties discussed above, as well as nullable spaceship and mission fields with corresponding return types.

Now that our schema is good to go, let's figure out what endpoints we'll need to use to update our data.