14. Mutations
10m

Overview

We've seen the power of specific and expressive queries that let us retrieve exactly the data we're looking for, all at once. But in is just one part of the equation.

When we want to actually change, insert, or delete data, we need to reach for a new tool: .

In this lesson, we will:

  • Explore syntax and write an to create a new listing
  • Learn about input types
  • Learn about response best practices

Mutations in Airlock

Onward to the next feature in our Airlock API: creating a new listing.

A mockup showing a view that lets us create a new listing by specifying its pertinent properties

Our REST API comes equipped with an endpoint that allows us to create new listings: POST /listings.

This method accepts a listing property on our request body. It should contain all of the properties relevant to the listing, including its amenities. Once the listing has been created in the database, this endpoint returns the newly-created listing to us.

All right, now how do we enable this functionality in ?

Designing mutations

Much like the Query type, the Mutation type serves as an entry point to our schema. It follows the same syntax as the , or , that we've been using so far.

We declare the Mutation type using the type keyword, then the name Mutation. Inside the curly braces, we have our entry points, the we'll be using to mutate our data.

Let's open up schema.graphql and add a new Mutation type.

schema.graphql
type Mutation {
}

For the of the Mutation, we recommend starting with a verb that describes the specific action of our update (such as add, delete, or create), followed by whatever data the acts on.

We'll explore how we can create a new listing, so we'll call this createListing.

type Mutation {
"Creates a new listing"
createListing: #TODO
}

For the return type of the createListing , we could return the Listing type; it's the we want the to act upon. However, we recommend following a consistent Response type for responses. Let's see what this looks like in a new type.

The Mutation response type

Return types for Mutation usually start with the name of the , followed by Payload or Response. Don't forget that type names should be formatted in PascalCase!

Following convention, we'll name our type CreateListingResponse.

type CreateListingResponse {
}

We should return the that we're mutating (Listing, in our case), so that clients have access to the updated object.

type CreateListingResponse {
listing: Listing
}

Note: Though our acts upon a single Listing object, it's also possible for a to change and return multiple objects at once.

Notice that the listing returns a Listing type that can be null, because our might fail.

To account for any partial errors that might occur and return helpful information to the client, there are a few additional we can include in a response type.

  • code: an Int that refers to the status of the response, similar to an HTTP status code.

  • success: a Boolean flag that indicates whether all the updates the was responsible for succeeded.

  • message: a String to display information about the result of the on the client side. This is particularly useful if the mutation was only partially successful and a generic error message can't tell the whole story.

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

type CreateListingResponse {
"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!
"The newly created listing"
listing: Listing
}

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

type Mutation {
"Creates a new listing"
createListing: CreateListingResponse!
}

The Mutation input

To create a new listing, our needs to receive some input.

Let's think about the kind of input this createListing would expect. We need all of the details about the listing itself, such as title, costPerNight, numOfBeds, amenities and so on.

We've used a before in the Query.listing : we passed in a single called id.

type Query {
listing(id: ID!): Listing
}

But createListing takes more than one . One way we could tackle this is to add each argument, one-by-one, to our createListing . But this approach can become unwieldy and hard to understand. Instead, it's a good practice to use input types as for a .

Exploring the input type

The input type in a is a special that groups a set of together, and can then be used as an argument to another . Using input types helps us group and understand , especially for .

To define an input type, use the input keyword followed by the name and curly braces ({}). Inside the curly braces, we list the and types as usual. Note that fields of an input type can be only a , an enum, or another input type.

input CreateListingInput {
}

Next, we'll add properties. To flesh out the listing we're about to create, let's send all the relevant details. We'll need: title, description, numOfBeds, costPerNight, and closedForBookings.

input CreateListingInput {
"The listing's title"
title: String!
"The listing's description"
description: String!
"The number of beds available"
numOfBeds: Int!
"The cost per night"
costPerNight: Float!
"Indicates whether listing is closed for bookings (on hiatus)"
closedForBookings: Boolean
}

We also need to specify the amenities our listing has to offer. Notice that the amenity options in our mock-up for creating a new listing are pre-defined; we can only select from existing options. Behind the scenes, each of these amenities has a unique ID identifier. For this reason, we'll add an amenityIds to CreateListingInput with a type of [ID!]!.

input CreateListingInput {
"The listing's title"
title: String!
"The listing's description"
description: String!
"The number of beds available"
numOfBeds: Int!
"The cost per night"
costPerNight: Float!
"Indicates whether listing is closed for bookings (on hiatus)"
closedForBookings: Boolean
"The Listing's amenities"
amenities: [ID!]!
}

Note: You can learn more about the input type, as well as other types and features in Side Quest: Intermediate Schema Design.

Using the input

To use an input type in the schema, we can set it as the type of a . For example, we can update the createListing to use CreateListingInput type like so:

type Mutation {
"Creates a new listing"
createListing(input: CreateListingInput!): CreateListingResponse!
}

Notice that the CreateListingInput is non-nullable. To run this , we actually need to require some input!

Building the ListingAPI method

As we've done for other requests, we'll build a method to manage this REST API call to create a new listing.

Back in datasources/listing-api.ts, let's add a new method for this .

datasources/listing-api.ts
createListing() {
// TODO
}

This time, because the endpoint uses the POST method, we'll use the this.post helper method from RESTDataSource instead of this.get.

Next, we'll pass our endpoint to this method: "listings"

listing-api.ts
createListing() {
return this.post("listings");
}

Our method will receive a new listing , which is of type CreateListingInput. We can import this type from types.ts.

import { Amenity, Listing, CreateListingInput } from "../types";

Then let's update the createListing method to receive the new listing.

createListing(listing: CreateListingInput) {
// method logic
}

We can pass a second to the this.post method to specify a request body. Let's add those curly braces now, and specify a property called body, which is another object.

listing-api.ts
createListing(listing: CreateListingInput) {
return this.post("listings", {
body: {}
});
}

Inside of this object, we'll pass our listing.

return this.post("listings", {
body: { listing },
});

Note: We're using shorthand property notation with implied keys, because we've named our constant with the matching key (listing).

Now we can take care of our method's return type. When the listing is created successfully, this endpoint will return a Promise that resolves to the newly-created listing object. So we can annotate our method with a return type of Promise<Listing>.

createListing(listing: CreateListingInput): Promise<Listing> {
return this.post("listings", {
body: {
listing
}
});
}

Connecting the dots in our resolver

Jump back into the resolvers.ts file. We'll add a new entry to our resolvers object called Mutation.

resolvers.ts
Mutation: {
// TODO
},

Let's add our createListing .

resolvers.ts
Mutation: {
createListing: (parent, args, contextValue, info) => {
// TODO
}
},

We won't need the parent or info parameters here, so we'll replace parent with _ and remove info altogether.

resolvers.ts
createListing: (_, args, contextValue) => {
// TODO
},

We know from our Mutation.createListing schema that this will receive an called input. We'll destructure args for this property. And while we're here, we'll also destructure contextValue for the dataSources property.

resolvers.ts
createListing: (_, { input }, { dataSources }) => {
// TODO
},

Now we'll call the createListing method from the listingAPI , passing it our input.

resolvers.ts
createListing: (_, { input }, { dataSources }) => {
dataSources.listingAPI.createListing(input);
},

We're not returning anything from this method just yet, so we might see some errors. In our schema we specified that the Mutation.createListing should return a CreateListingResponse type.

schema.graphql
type CreateListingResponse {
"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!
"The newly created listing"
listing: Listing
}

This means that the object we return from our needs to match this shape. Let's start by setting up the object that we'll return in the event that our succeeds.

resolvers.ts
createListing: (_, { input }, { dataSources }) => {
dataSources.listingAPI.createListing(input);
// everything succeeds with the mutation
return {
code: 200,
success: true,
message: "Listing successfully created!",
listing: null, // We don't have this value yet
}
},

Checking the response

Now, let's take a look at the response from our API call. We'll need to make our entire async in order to await the results of calling dataSources.listingAPI.createListing().

resolvers.ts
createListing: async (_, { input }, { dataSources }) => {
const response = await dataSources.listingAPI.createListing(input);
console.log(response);
// everything succeeds with the mutation
return {
code: 200,
success: true,
message: "Listing successfully created!",
listing: null, // We don't have this value yet
}
},

In Sandbox, let's put together a .

mutation CreateListing($input: CreateListingInput!) {
createListing(input: $input) {
code
success
message
}
}

And add the following to the Variables panel.

{
"input": {
"title": "Mars' top destination",
"description": "A really cool place to stay",
"costPerNight": 44.0,
"amenities": ["am-1", "am-2"],
"numOfBeds": 2
}
}

When we run the , we'll see that this actually works as expected! We can clearly see the values we set for code, success, and message in our happy path.

And in the terminal of our running server, we'll see the response from the API logged out: it's our newly-created listing!

{
id: '22ff64fe-41d4-4754-acbb-22ac89e27620',
title: "Mars' top destination",
description: 'A really cool place to stay',
costPerNight: 44,
hostId: null,
locationType: null,
numOfBeds: 2,
photoThumbnail: null,
isFeatured: null,
latitude: null,
longitude: null,
closedForBookings: null,
amenities: [
{
id: 'am-1',
category: 'Accommodation Details',
name: 'Interdimensional wifi'
},
{ id: 'am-2', category: 'Accommodation Details', name: 'Towel' }
]
}

This means we can return the whole value of the response as the listing property in the object we return.

return {
code: 200,
success: true,
message: "Listing successfully created!",
listing: response,
};

Now let's build out the sad path—when our doesn't go as expected.

Handling the sad path

Returning to our Mutation.createListing , we'll account for the error state.

We'll start by wrapping everything we've written so far in a try/catch block.

resolvers.ts
try {
const response = await dataSources.listingAPI.createListing(input);
return {
code: 200,
success: true,
message: "Listing successfully created!",
listing: response,
};
} catch (err) {}

Inside of the catch block, we'll return an object with some different properties.

resolvers.ts
try {
// try block body
} catch (err) {
return {
code: 500,
success: false,
message: `Something went wrong: ${err.extensions.response.body}`,
listing: null,
};
}

Here's how your entire function should look.

To test our sad path, let's try creating a listing with a non-existent amenity ID.

Back in Sandbox, let's update our to include more information about the listing we'll attempt to create.

A mutation, doomed to fail
mutation CreateListing($input: CreateListingInput!) {
createListing(input: $input) {
code
success
message
listing {
title
description
costPerNight
amenities {
name
category
}
}
}
}

Then let's update our Variables panel; this time, we'll update our listing's "numOfBeds" to be zero.

{
"input": {
"title": "Mars' top destination",
"description": "A really cool place to stay",
"costPerNight": 44.0,
"amenities": ["am-1", "am-2"],
"numOfBeds": 0
}
}

When we run the , we'll see the values we expect: the failed, and our error message comes through loud and clear. Something went wrong: 503: Service Unavailable!

With our sad path validated, let's revert our change to the Variables panel—we need at least one bed available at our listing!

{
"input": {
"title": "Mars' top destination",
"description": "A really cool place to stay",
"costPerNight": 44.0,
"amenities": ["am-1", "am-2"],
"numOfBeds": 2
}
}

Now let's run that one more time and see if all of our listing data is accounted for.

A mutation, presumed to succeed
mutation CreateListing($input: CreateListingInput!) {
createListing(input: $input) {
code
success
message
listing {
title
description
costPerNight
amenities {
name
category
}
}
}
}

Run the and... data!

Bravo, you've done it!

Practice

Which of these are good names for mutations based on the recommended conventions above?
In the mutation response type (CreateListingResponse), why is the modified object's return type (Listing) nullable?
How can we use the input type in our schema?
When creating an input type for a mutation, what naming convention is commonly used?

Key takeaways

  • are write used to modify data.
  • Naming usually starts with a verb that describes the action, such as "add," "delete," or "create."
  • It's a common convention to create a consistent response type for responses.
  • in often require multiple to perform actions. To group arguments together, we use a GraphQL input type for clarity and maintainability.

Journey's end

Task!

You've built a API! You've got a working , jam-packed with intergalactic listings, that uses a REST API as a . You've written queries and , and learned some common GraphQL conventions along the way. You've explored how to use GraphQL , , and input types in your schema design. Take a moment to celebrate; that's a lot of learning!

But the journey doesn't end here! When you're ready to take your API even further, jump into the next course in this series: Federation with TypeScript & Apollo Server.

Thanks for joining us in this course; we hope to see you in the next one!

Previous

Share your questions and comments about this lesson

This course is currently in

beta
. Your feedback helps us improve! If you're stuck or confused, let us know and we'll help you out. All comments are public and must follow the Apollo Code of Conduct. Note that comments that have been resolved or addressed may be removed.

You'll need a GitHub account to post below. Don't have one? Post in our Odyssey forum instead.