3. The input type
5m

Overview

In Odyssey Lift-off III, we learned that we can define s for a in our , which the 's can use. In that course, we only defined a single for a , so our stayed pretty simple and clean.

But in Airlock, some of our s require several s all at once. How can we keep our easy to read while also providing our s the data they need? The answer: with input types!

In this lesson, we will:

  • Learn about the input type
  • Discover the benefits of using an input type for mutations
  • See an example of how the input type is used in the Airlock codebase

What is the input type?

The input type in a GraphQL is a special that groups a set of s together, and can then be used as an to another .

Using input types helps us group and understand s, especially for s. For example, when creating a listing in Airlock, we know the needs to include a bunch of data about the listing (title, description, photo thumbnail, number of beds, cost per night, location type, and amenities). We could list out all those s inside the createListing , but that can get unwieldy and hard to understand.

Instead, we can create an input type called CreateListingInput and list all the necessary s there. That way, we can keep the definition clear, and we can also reuse that input type in other s that require the same set of s.

Defining an input

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

Here's an example of another input type from the Airlock :

server/schema.graphql
input SearchListingsInput {
checkInDate: String!
checkOutDate: String!
numOfBeds: Int
page: Int
limit: Int
sortBy: SortByCriteria # this is an enum type
}

Using the input

To use an input type in the , we can set it as the type of a . For example, the searchListings query uses the SearchListingsInput type like so:

server/schema.graphql
type Query {
# ...
"Search results for listings that fit the criteria provided"
searchListings(criteria: SearchListingsInput): [Listing]!
# ...
}

Note: Input types can be reused in multiple s, but be careful when using the same input type for both queries and s! Some s that may be required in s may not be required for queries.


For more details, check out the Apollo docs on input types.

See it in the Airlock codebase

There are multiple inputs defined in the Airlock . Check them out in the server/schema.graphql file.

  • What do you notice about the existing inputs?
  • How are the inputs used in the client code?

Practice

How can we use the input type in our schema?

Key takeaways

  • The input type is a special object type used as arguments to fields. This allows us to group and understand all of our arguments together, especially for mutations.

Up next

In the next lesson, we'll learn another tool for grouping related attributes: interfaces.

Previous
Next